node.js javascript获取系统时区中的时间戳而不是UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16393326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript get timestamp in system timezone not in UTC
提问by user1229351
Hi all im looking for a way to get current system time in a timestamp. i used this to get timestamp:
大家好,我正在寻找一种在时间戳中获取当前系统时间的方法。我用它来获取时间戳:
new Date().getTime();
but it return the time in UTC timezone not the timezone that server use
但它返回的是 UTC 时区的时间,而不是服务器使用的时区
is there any way to get timestamp with system timezone?
有没有办法用系统时区获取时间戳?
回答by Noah
Check out moment.js http://momentjs.com/
查看moment.js http://momentjs.com/
npm install -S moment
New moment objects will by default have the system timezone offset.
默认情况下,新的时刻对象将具有系统时区偏移量。
var now = moment()
var formatted = now.format('YYYY-MM-DD HH:mm:ss Z')
console.log(formatted)
回答by ScottyC
Since getTime returns unformatted time in milliseconds since EPOCH, it's not supposed to be converted to time zones. Assuming you're looking for formatted output,
由于 getTime 自 EPOCH 以来以毫秒为单位返回未格式化的时间,因此不应将其转换为时区。假设您正在寻找格式化的输出,
Here is a stock solution without external libraries, from an answer to a similar question:
这是一个没有外部库的库存解决方案,来自对类似问题的回答:
the various
toLocale…Stringmethods will provide localized output.d = new Date(); alert(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) alert(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004 alert(d.toLocaleDateString()); // -> 02/28/2004 alert(d.toLocaleTimeString()); // -> 23:45:26
各种
toLocale…String方法将提供本地化的输出。d = new Date(); alert(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) alert(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004 alert(d.toLocaleDateString()); // -> 02/28/2004 alert(d.toLocaleTimeString()); // -> 23:45:26
And extra formatting options can be provided if needed.
如果需要,可以提供额外的格式选项。
回答by Nilisha Maheshwari
Install the module 'moment' using:
使用以下命令安装模块“时刻”:
npm install moment --save
And then in the code add the following lines -
然后在代码中添加以下几行 -
var moment = require('moment');
var time = moment();
var time_format = time.format('YYYY-MM-DD HH:mm:ss Z');
console.log(time_format);

