我真的需要使用javascript获取赫尔辛基和莫斯科当前的时间,但不管当地的时区。我想知道该怎么做?也许有人有一个例子吗?
格式为:
2011年11月1日 21时31分零零秒
谢谢。答案 0 :(得分:3)
// 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之后。
[编辑]
这可能会更好:(请注意,您必须自己从recv'd 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
[/编辑]
答案 1 :(得分:2)
当您提前知道偏移时,以下功能有效:
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"
上述内容将始终适用于莫斯科,后者不再遵守夏令时,但您需要了解为赫尔辛基制定等效通用解决方案的一年中的什么时间。