简体   繁体   English

如何获取moment.js以UTC时间(以毫秒为单位)输出格式化时间?

[英]How can I get moment.js to output a formatted time in UTC time with milliseconds?

var end, moment, timeFormat;
moment = require('moment');
end = moment.utc('2016-11-29T23:59:59.999');
console.dir(end.format());
timeFormat = 'YYYY-MM-DDThh:mm:ss.SSS';
console.dir(end.format(timeFormat));

Output: 输出:

'2016-11-29T23:59:59Z'
'2016-11-29T11:59:59.999'

What I really need: 我真正需要的是:

'2016-11-29T23:59:59.999'

Why is there a 12 hour difference between those 2 outputs? 为什么这两个输出之间有12小时的差异? I could just add 12 hours to it, but that is hacky. 我可以再加上12个小时,但这很麻烦。 I don't understand why moment is suddenly subtracting 12 hours from my date as soon as I give it a format. 我不明白为什么输入格式后瞬间会突然从我的约会中减去12小时。 Seems unlikely this is a bug; 似乎不太可能是错误; more likely me misunderstanding what Moment is doing. 我很可能会误会Moment在做什么。

My timezone is GMT+8. 我的时区是GMT + 8。

Because you are using hh (01-12) instead of HH (00-23); 因为您使用的是hh (01-12)而不是HH (00-23); see the Moment.js format() docs. 请参阅Moment.js format()文档。

Here is a working example: 这是一个工作示例:

 var end, wrongTimeFormat, timeFormat; end = moment.utc('2016-11-29T23:59:59.999'); console.dir(end.format()); wrongTimeFormat = 'YYYY-MM-DDThh:mm:ss.SSS'; timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS'; console.dir(end.format(wrongTimeFormat)); console.dir(end.format(timeFormat)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment.min.js"></script> 

According to the Moment.js docs , lowercase hh will produce hours in the 01-12 range, which are meant to be used in conjunction with am/pm. 根据Moment.js文档 ,小写hh会产生01-12范围内的小时,这些小时与am / pm结合使用。 You need capital HH (00-23, "military time"), as in 您需要大写HH (00-23,“军事时间”),例如

timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS'

使用大写HH

timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM