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

时间:2020-05-05 03:28:54

标签: javascript jquery datetime highcharts momentjs

我正在尝试从ISO日期中提取月份名称。

我正在尝试:

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

我得到invalid date

如何从ISO日期中提取月份名称和星期编号?

3 个答案:

答案 0 :(得分:3)

正如我在评论中提到的那样,请改用.format()

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

已经有了使用moment.js进行此操作的答案,因此出于完整性考虑,这里使用 toLocaleString 。请注意,输入字符串必须符合format specified by ECMA-262

要考虑的一个问题是您要使用UTC月份还是用户的本地月份。对于时区偏移量为负的用户,“ 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);

通过将时区指定为UTC,可以确保时区偏移量为负的用户获得1月,而不是其本地月份为12月。