I stumbled upon an interesting issue with moment.js in a node.js environment. Basically, I'm trying to get the time from epoch for a date format "Friday 24 Aug", but I receive NaN as a result. Here is my node.js code:
const moment = require("moment");
console.log(moment("Friday 24th Aug", "dddd Do MMM").valueOf());
moment.js version: 2.23.0
nodejs version: v8.11.3
OS: Linux 16.04.1-Ubuntu
While if I try the same console line on a browser, works fine. Has anyone stumbled upon something like this?
EDIT: Apologies for the link, I used an already created jsfiddle which had moment.js version: 2.2.1. It seems it had "worked" in that version, but now it's changed: http://jsfiddle.net/fy8w62on/ (moment.js version 2.2.1)
答案 0 :(得分:1)
Friday 24th Aug
does not contain a year so moment has to guess what year it is and uses the current year for the guess.
If it is 2018 at the time when you run the code then valueOf
would not return NaN
.
But it is 2019 so Friday 24th Aug
of 2019 is not valid.
答案 1 :(得分:1)
valueOf()
给出NaN
,因为您的矩对象(moment("Friday 24th Aug", "dddd Do MMM"
)是invalid。
请注意,如文档的Default部分所述:
您可以创建一个矩对象,仅指定某些单位,其余的将默认为当前的日期,月份或年份,或小时,分钟,秒和毫秒的默认值为0。
因此一刻尝试创建一个代表2019-08-24
的实例(使用当年),但是它创建了Invalid Date
,因为2019-08-24
是星期六(使用default美国英语语言环境) ,而不是星期五(其他人已经在评论中说过)。
使用parsingFlags
,您将看到weekdayMismatch
设置为true
var m = moment("Friday 24th Aug", "dddd Do MMM");
console.log(m.valueOf()); // NaN
console.log(m.format()); // Invalid date
console.log(m.parsingFlags()); // Object with "weekdayMismatch": true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>