Marissa
Marissa

Reputation: 215

Moment.js isBefore function not working as expected

My console log is giving me an unexpected output.

var bool = (moment("2017-04-08 23:00:00").isBefore(moment("2017-04-09 01:00:00", 'day')));
console.log(bool);

The output is false, for some reason. According to the documentation, the following code should return true.

moment('2010-10-20').isBefore('2011-01-01', 'year')

Even if it's not a full year past, if it's a different year, my understanding is that it should return false. In my case, while it hasn't yet been 24 hours, it is a different day. Is there something I'm not understanding correctly?

Upvotes: 6

Views: 40792

Answers (3)

Mohammed Yasin
Mohammed Yasin

Reputation: 527

Similarly found the issue between chrome and safari browser, then I found that, the safari browser doesn’t validate properly when the date with timezone and microseconds value then I compare the date like below

"2021-05-11 22:00:23"

instead of using the date with microseconds and timezone

"2021-05-11 22:00:23.000 +0000"

then it works fine for me

Upvotes: 0

Sam Gomena
Sam Gomena

Reputation: 1479

The moment(...) argument does not accept the 'day' parameter.

Instead, you should be calling isBefore(...) with the day parameter like so:

moment(...).isBefore(moment(...), 'day'));

More info can be found at the moment docs here.

Upvotes: 5

Lyubomir
Lyubomir

Reputation: 20027

@Oliver Charlesworth is right, moment() doesn't accept 'day' as a second argument. Have a look here and scroll down for all its valid signatures.


With that being said, you can either convert

isBefore(moment("2017-04-09 01:00:00", 'day'));

to

isBefore(moment('2017-04-09 01:00:00'), 'day');

or to

isBefore('2017-04-09 01:00:00', 'day');

Both work.


Here is the signature for isBefore.

Upvotes: 12

Related Questions