开发者

Converting my javascript datetime to UTC from PST

开发者 https://www.devze.com 2023-02-20 13:35 出处:网络
I\'m going out of my mind dealing with my local (PST) time zone and making calls to a webservice that is in UTC.

I'm going out of my mind dealing with my local (PST) time zone and making calls to a webservice that is in UTC.

The webservice takes a start and end date in format of "2011-02-09T12:00:00", and the current code uses starttime=30 days ago, and endtime=now.

Here's the code:

var s = new Date(); 
var e = new Date(); 

s.setTime(d.getTime() - 30 * 24 * 60 * 60 * 1000);

var startdate = String.Format("datetime'{0:df(yyyy-MM-dd)}T{0:df(HH:mm:ss)}'", s);  
var enddate = String.Format("datetime'{0:df(yyyy-MM-dd)}T{0:df(HH:mm:ss)}'", e);

var url = String.Format("http://foo.com/webservice.svc/data?start={1}&end={2}&$format=json", startdate, enddate);
var obj = GetJsonObjectFromServer(url);

I've tried just adding 25,200,000 ms to d and b but that's resulting in s being returned as an invalid date (presumably because it's putting it in the future maybe?).

Since it's using PST, my local time zone, the webservice I'm pas开发者_运维技巧sing these params into isn't returning all the data since it's missing an 8 hour span since server is in UTC.

I've tried a bunch of UTC methods, but problem is getting it back into the format I need for the webservice. I'd appreciate more direct guidance instead of just pointing to Javascript UTC methods.

There's something simple I'm missing here and would love help!


JavaScript has a UTC date method, just use that.

<script type="text/javascript">

var d=Date.UTC(2005,7,8);
document.write(d);

</script>

From: http://www.w3schools.com/jsref/jsref_utc.asp


If you pass your dates as Date objects, then the web service should handle the date/time conversions on deserialization. This, at least, is how it works with web services in asp.net.

Be careful going the other way, though, as dates being returned from SQL Server are NOT encoded for time zones, and the zone must be set before serialization for the auto-conversion to work going to the browser.


I faced similar problem, hope description of the same would help u. (Not sure this the rootcause for your problem).

The expression "30 * 24 * 60 * 60 * 1000" actually evaluates to an integer and many a times results in overflow. Converting it to long expression solved the problem for me. In other words add "L" to one of the constants above. "30 * 24 * 60 * 60 * 1000L".


Turns out that just adding 7 hours in milliseconds was the easiest approach. i.e.:

// get start date to be 30 days ago
var foo = (30 * 24 * 60 * 60 * 1000);
s.setTime(s.getTime() - foo + 25200000);
e.setTime(e.getTime() + 25200000);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号