我尝试使用node.js和timezone-js
实现world-clock出于奇怪的原因,我找不到任何让它成功的例子,比如hello-world program。
所以这是我的尝试:
var timezoneJS = require('timezone-js');
timezoneJS.timezone.zoneFileBasePath = './tz';
timezoneJS.timezone.init();
var getTime = function(timezone)
{
var UTC = new timezoneJS.Date(new Date(), 'Etc/UTC'); //for unknown reason this works only for Etc/UTC
var YYYY = UTC.getFullYear();
var MM = UTC.getMonth() + 1;
var DD = UTC.getDate();
var hh = UTC.getHours();
var mm = UTC.getMinutes();
var ss = UTC.getSeconds();
var dt = new timezoneJS.Date(YYYY, MM, DD, hh, mm, ss, timezone);
var date = dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate();
var time = ('0' + dt.getHours()).slice(-2) + ':' + ('0' + dt.getMinutes()).slice(-2) + ':' + ('0' + dt.getSeconds()).slice(-2);
var datetime = date + ' ' + time;
return datetime;
};
log(getTime('Europe/London'));
log(getTime('America/New_York'));
结果如下:
$ node app
'2014/7/16 14:30:40'
'2014/7/16 14:30:40'
伦敦和纽约同样如此。这是怎么发生的?并让我知道如何解决。
感谢。
答案 0 :(得分:0)
您应该可以省略函数的第一部分,只需执行此操作:
var dt = new timezoneJS.Date(Date.now, timezone);
它无法正常工作的原因是您在两个不同的时区将日期初始化为相同的年/月/日/小时/分钟/秒。换句话说 - 它们不代表当前时间 - 它们被错误地移动了UTC偏移量。
您可能还会考虑moment-timezone或one of the other libraries listed here。