简体   繁体   English

格式化时刻 JS 日期减去一天

[英]format moment JS date substracts one day

I am currently using moment.js and I am facing a problem to format a date to DD MMM as it's giving me one day less that the original date.我目前正在使用 moment.js 并且我面临将日期格式化为DD MMM的问题,因为它给我的时间比原始日期少了一天。 I am making the transformation with the next line:我正在使用下一行进行转换:

moment(date).format('DD MMM')

As an example, date is 2019-09-12T00:00:00Z and for this date, moment is giving me: 11 sept例如,日期是2019-09-12T00:00:00Z ,对于这个日期,时刻给了我: 11 月

Then, why 11 and not 12?那么,为什么是 11 而不是 12? is this related with the fact that the hour is 00:00:00Z ?这与小时是 00:00:00Z 的事实有关吗? In that case, how should be threated?既然如此,又该如何受到威胁?

Thanks in advance提前致谢

Yes, this is almost surely because it is formatting the date in your current time zone, but the original time is expressed in UTC — the Z at the end means "zero time zone offset from UTC".是的,这几乎可以肯定,因为它正在格式化您当前时区的日期,但原始时间以 UTC 表示——末尾的Z表示“与 UTC 的零时区偏移”。 For reference, a date with a time zone would, instead of Z have something like -06:00 at the end.作为参考,带有时区的日期会在末尾而不是Z有类似-06:00的内容。

I believe you can solve your issue by using the moment.utc method, which causes prints of that date to be printed in UTC rather than your local timezone.我相信您可以通过使用moment.utc方法来解决您的问题,这会导致该日期的打印件以 UTC 而不是您的本地时区打印。

Compare printing the date (with timezone included) without the .utc : (my timezone is UTC -6)比较没有.utc打印日期(包括时区):(我的时区是 UTC -6)

console.log(moment('2019-09-12T00:00:00Z').format('DD MMM Z'));
=> 11 Sep -06:00

vs with .utc :.utc

console.log(moment.utc('2019-09-12T00:00:00Z').format('DD MMM Z'));
=> 12 Sep +00:00

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

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