简体   繁体   English

如何使用 Moment js 从 ISO 日期获取月份名称

[英]How to get month name from ISO date using moment js

I am trying to extract the month name from ISO dates.我正在尝试从 ISO 日期中提取月份名称。

I am trying this:我正在尝试这个:

moment('2020-01-01T00:00:00.000Z', 'YYYY-MM-DDTHH:mm:ss.SSS[Z]').month('MMMM');

I am getting invalid date .我的invalid date

How can I extract the month name and the week number from ISO dates?如何从 ISO 日期中提取月份名称和周数?

As I mentioned in a comment, use .format() instead:正如我在评论中提到的,请改用.format()

moment('2020-01-01T00:00:00.000Z', 'YYYY-MM-DDTHH:mm:ss.SSS[Z]').format('MMMM');

You should use format() method.您应该使用format()方法。 https://momentjs.com/docs/#/parsing/ https://momentjs.com/docs/#/parsing/

var month = moment('2020-01-01T00:00:00.000Z', 'YYYY-MM-DDTHH:mm:ss.SSS[Z]').format('MMMM');

There is already an answer for doing this with moment.js, so for completeness here's one for using toLocaleString .使用 moment.js 已经有一个答案,所以为了完整起见,这里有一个使用toLocaleString的答案。 Note that the input string needs to be compliant with the format specified by ECMA-262 .请注意,输入字符串需要符合ECMA-262 指定的格式

One issue to consider is whether you want the UTC month or user's local month.要考虑的一个问题是您想要 UTC 月份还是用户的本地月份。 For users with a negative timezone offset, '2020-01-01T00:00:00.000Z' is in December, not January, eg:对于时区偏移为负的用户,“2020-01-01T00:00:00.000Z”是在 12 月,而不是 1 月,例如:

 let d = new Date('2020-01-01T00:00:00.000Z'); // Zero offset let utcMonth = d.toLocaleString('en',{month:'long', timeZone:'UTC', timeZoneName: 'long'}); // Negative offset let spMonth = d.toLocaleString('en',{month:'long', timeZone:'America/Sao_Paulo', timeZoneName: 'long'}); console.log('The UTC month is: ' + utcMonth + '\nSao Paulo month is: ' + spMonth);

By specifying the timezone as UTC, it ensures that users with a negative timezone offset get January, not their local month which will be December.通过将时区指定为 UTC,它可以确保具有负时区偏移量的用户获得 1 月,而不是他们的本地月份,即 12 月。

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

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