momentjs isBefore返回不良结果

时间:2016-08-20 16:23:01

标签: javascript date momentjs

我正在尝试检查给定日期是否在今天的日期之前:

const today = moment(new Date(), "YYYY-MM-DD", true);
const isBeforeToday = moment("2016-08-20", "YYYY-MM-DD", true).isBefore(today));

isBeforeToday变量的值为true,显然不正确。今天是8月20日和8月20日不是8月20日之前:)。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

8月20日不是在8月20日之前,但是:

您正在构建两种不同的日期:一种是时间,一种是没有,而午夜(当前)在当前时间之前。

const today = moment(new Date(), "YYYY-MM-DD", true)
console.log(JSON.stringify(today, null, 2))
// >> "2016-08-20T16:28:23.020Z"

const tmp = moment("2016-08-20", "YYYY-MM-DD", true)
console.log(JSON.stringify(tmp, null, 2));
// >> "2016-08-20T04:00:00.000Z"

const isBeforeToday = tmp.isBefore(today)
console.log(isBeforeToday);
// >> true

您正在使用Date构建您的第一个时刻,而不是字符串;没有什么可以解析的。因此,你的时刻有所有日期字段。如果您创建了没有时间字段的Date对象,则可以获得预期的结果:

const today2 = moment(new Date(2016, 07, 20), "YYYY-MM-DD", true)
console.log(JSON.stringify(today2, null, 2))
// >> "2016-08-20T04:00:00.000Z"

const tmp2 = moment("2016-08-20", "YYYY-MM-DD", true)
console.log(JSON.stringify(tmp2, null, 2));
// >> "2016-08-20T04:00:00.000Z"

const isBeforeToday2 = tmp2.isBefore(today2)
console.log(isBeforeToday2);
// >> false