Millisecond to various GMT timezones conversion
I have a time in millisecond i.e. 1274203800000, now i want to convert it into GMT + 10 in javascript.
currently i am using following code to do that
var milliseconds=1274203800000;
var offset='+10';
var d = new Date(milliseconds);
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
var re开发者_如何学JAVAsult=nd.toLocaleString();
alert(result);
Above code evaluates to "Wednesday, May 19, 2010 3:30:00 AM" date but this is not the correct output as "Tuesday, May 18, 2010 3:30:00 AM" (not sure about the AM or PM in this case) is the right one. But i don't know whats the problem over here.
My current localtimezone is GMT+0530.
Here i can get the desired output
var milliseconds=1274203800000;
var offset=10;
var d = new Date(milliseconds+(3600000*offset));
alert(d.toUTCString());
Initial Input: Tue, 18 May 2010 17:30:00 GMT
Desired Output: Wed, 19 May 2010 03:30:00 GMT
Timestamps are kept in UTC. 1274203800000
corresponds to 2010-05-18 17:30:00 UTC
, which is indeed 2010-05-19 03:30:00 UTC+10
. I don't know how you would get 2010-05-18 03:30:00
from that timestamp — it would have to be UTC-14, and no country has that as a timezone.
(Aside: in your code as it stands, the first use of new Date().getTime()
does nothing as it'll return the same milliseconds
.)
ETA: You don't get any control over the format of toLocaleString()
, the format comes from the user's OS and browser settings. On my machine here, I get 12-hour clock and a timezone name included. Which is annoying, as I think 12-hour time is a total disaster that should be wiped from the face of the planet and the timezone's actually wrong.
But anyway, if you want a specific time format you'll have to create it yourself, as JS offers no formatting options. This can be quite tedious:
var daynames= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var monthnames= ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
function padLeft(s, l, c) {
return new Array(l-s.length+1).join(c || ' ')+s;
};
function to12HourTime(x) {
var dn= daynames[x.getUTCDay()];
var mn= monthnames[x.getUTCMonth()];
var d= padLeft(''+x.getUTCDate(), 2, '0');
var y= padLeft(''+x.getUTCFullYear() ,4, '0');
var h= x.getUTCHours();
var m= padLeft(''+x.getUTCMinutes(), 2, '0');
var s= padLeft(''+x.getUTCSeconds(), 2, '0');
var p= h>=12? 'PM' : 'AM';
h= (h+11)%12+1;
return dn+', '+mn+' '+d+', '+y+' '+h+':'+m+':'+s+' '+p;
}
var t= 1274203800000;
var d= new Date(t+1000*60*60*10);
alert(to12HourTime(d));
// Wednesday, May 19, 2010 3:30:00 AM
1274203800000 in Epoch is Tue, 18 May 2010 17:30:00 GMT
(you can use this Epoch converter http://www.epochconverter.com/ )
Now, if you do:
var milliseconds=1274203800000;
var d = new Date(milliseconds);
alert(d.toUTCString());
You get the right GMT time.
精彩评论