javascript - How to get month name from ISO date using moment js - Stack Overflow

I am trying to extract the month name from ISO dates. I am trying this:moment('2020-01-01T00:00:00

I am trying to extract the month name from ISO dates.

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.

How can I extract the month name and the week number from ISO dates?

I am trying to extract the month name from ISO dates.

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.

How can I extract the month name and the week number from ISO dates?

Share Improve this question asked May 5, 2020 at 3:28 nb_nb_nbnb_nb_nb 1,38118 silver badges53 bronze badges 5
  • 2 I can't reproduce this. You should do this instead though: .format('MMMM'); – mechanical_meat Commented May 5, 2020 at 3:38
  • month gets or sets the day of the month. If you provide a value, it sets the month. Use format. – RobG Commented May 5, 2020 at 3:42
  • @mechanical_meat, if you submit this as an answer, I can accept it. – nb_nb_nb Commented May 5, 2020 at 3:43
  • @noob: ok, I will. Thanks. – mechanical_meat Commented May 5, 2020 at 3:45
  • @noob—do you want the local month or UTC month? If you're west of Greenwich, 2020-01-01T00:00:00.000Z may return December. ;-) – RobG Commented May 5, 2020 at 3:45
Add a ment  | 

3 Answers 3

Reset to default 3

As I mentioned in a ment, use .format() instead:

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

You should use format() method. https://momentjs./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 pleteness here's one for using toLocaleString. Note that the input string needs to be pliant with the format specified by ECMA-262.

One issue to consider is whether you want the UTC month or user's local month. For users with a negative timezone offset, '2020-01-01T00:00:00.000Z' is in December, not January, e.g.:

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745038404a4607661.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信