问题
i really need to get Helsinki and Moscow current time using javascript but regardless of local timezone. I wonder how to do that? Maybe anyone has an example?
The format would be:
November 1, 2011 21:31:00
thank you.
回答1:
The following function works when you know the offset ahead of time:
var MOSCOW_OFF = 4; // hours
var MONTHS = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
// desired format => November 1, 2011 21:31:00
function getLocalTime(offset) {
var d = new Date();
d.setTime((new Date().getTime()) +
(d.getTimezoneOffset() * 60 * 1000) + // local offset
(1000 * 60 * 60 * offset)); // target offset
return MONTHS[d.getMonth()] + " " + d.getDate() + ", " +
d.getFullYear() + " " + d.toTimeString().split(" ")[0];
}
getLocalTime(MOSCOW_OFF); // => "November 2, 2011 01:22:27"
The above will always work for Moscow, which no longer observes a Daylight Savings Time, but you'd need to be aware of what time of year it is to make an equivalently generic solution for Helsinki.
回答2:
// create Date object for current location
d = new Date();
// convert to msec since Jan 1 1970
localTime = d.getTime();
// obtain local UTC offset and convertto msec
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// obtain and add destination's UTC time offset
// for example, Paris
// which is UTC + 1.0 hours
offset = 1.0;
paris = utc + (3600000*offset);
// convert msec value to date string
nd = new Date(paris);
document.writeln("Paris time is " + nd.toLocaleString() + "<br>");
(Sorry, don't know Helsinki offset, probably 2?)
Note that a negative return value from getTimezoneOffset() indicates that the current location is ahead of UTC, while a positive value indicates that the location is behind UTC.
[edit]
This may work better: (note that you will have to manipulate the format yourself from the recv'd helsinki variable
function getTZTime (tzOffset) {
local = new Date();
off = ( local.getTimezoneOffset() ) * 60 * 1000;
timeStamp = local.getTime() + off;
off += 1000 * 60 * 60 * tzOffset;
nd = new Date();
nd.setTime( timeStamp );
return (nd);
}
helsinki = getTZTime (2); // Helsinki is 2 TZ's from GMT
[/edit]
来源:https://stackoverflow.com/questions/7971813/get-helsinki-local-time-regardless-of-local-time-zone