我真的需要使用javascript获得赫尔辛基和莫斯科的当前时间,但不考虑当地时区。我想知道怎么做?有人能举个例子吗?
格式为:
2011年11月1日21:31:00
谢谢。
// 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>");
(抱歉,不知道赫尔辛基偏移量,可能是2?)
注意getTimezoneOffset()的负返回值表示当前位置在UTC之前,而正返回值表示当前位置在UTC之后。
[编辑]
这样做可能效果更好:(注意,您必须自己从接收到的helsinki
变量
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
(/编辑)当您提前知道偏移量时,以下函数可以工作:
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"
以上将始终适用于莫斯科,莫斯科不再遵守夏令时,但你需要知道它是一年中的什么时候,为赫尔辛基制定一个等效的通用解决方案。