johntrepreneur
johntrepreneur

Reputation: 4694

How to do a greater than or equal to with moments (moment.js) in javascript?

Basically, I want to do a myMoment >= yourMoment. There is no myMoment.isSameOrAfter and writing that out combining isSame and .isAfter is a bit lengthy.

What's the alternative? Convert moment to js date and use >= to compare?

Upvotes: 104

Views: 188107

Answers (5)

Jim Sosa
Jim Sosa

Reputation: 628

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

Upvotes: 4

Marianela Diaz
Marianela Diaz

Reputation: 99

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

Upvotes: 3

johntrepreneur
johntrepreneur

Reputation: 4694

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

myMoment.diff(yourMoment) >= 0

Close enough.

Upvotes: 72

tuananh
tuananh

Reputation: 755

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

Upvotes: 14

Daniel0b1b
Daniel0b1b

Reputation: 2321

You can use the isSameOrAfter method in momentjs:

moment1.isSameOrAfter(moment2);

Upvotes: 218

Related Questions