如何在 javascript 中做一个大于或等于瞬间(Moment.js)的代码?

基本上,我想做一个 myMoment >= yourMoment。没有 myMoment.isSameOrAfter,写出来结合 isSame.isAfter有点长。

还有什么选择? 将瞬间转换为 js 日期,然后使用 >=进行比较?

153017 次浏览

Okay, I just went with the moment.js .diff() function.

myMoment.diff(yourMoment) >= 0

Close enough.

You can use the isSameOrAfter method in momentjs:

moment1.isSameOrAfter(moment2);
let A = moment('2020-01-02');
let B = moment('2020-01-01');
let C = moment('2020-01-03');
console.log(A.diff(B, 'days'));// => 1
console.log(A.diff(C, 'days'));// => -1

The supported measurements are years, months, weeks, days, hours, minutes, and seconds momentjs.com

You could use isBetween function that compares one date in a range:

let foundDateInRange = moment('2022-01-15').isBetween('2022-01-01', '2022-01-30');

Console image using isBetween method

Moment does implement the valueOf() method. Therefor < <= > >= all can coerce moment into a native type. If you look at the actual implementations for isAfter or isBefore you'll see that's exactly what they do.

So you can just do myMoment >= yourMoment