Moment: the `isBefore` method is nondeterministic

Created on 6 Apr 2018  ·  5Comments  ·  Source: moment/moment

I found this while working on a calendar that needs to disable certain date ranges. It is sometimes off by one.

To reproduce:

  1. open chrome dev-tools, type in moment().isBefore(moment())
    Run it over and over again, it should always be false, but sometimes shows true. This does not appear to happen with the isAfter method. Below is a screenshot.

image

Bug

All 5 comments

It looks like isBefore is behaving correctly but somehow the two moment() objects are sometimes created with the second one having the earlier date. This is the check that's returning disparate results:
https://github.com/moment/moment/blob/develop/src/lib/moment/compare.js#L26

I see, thanks for looking into it and getting back to me!

I think it depends on the exact millisecond the moments are created. The fact that the second is ever created after the first feels like a browser bug.

There is a more extensive conversation around this topic here: https://github.com/moment/moment/issues/2697

The fact that the second is ever created after the first feels like a browser bug.

Looks fine to me.

Compare moment().isBefore(moment()) with:
somethingThrowingAnError().method(somethingWithSideEffects())
Or even:
somethingReturningNull().method(somethingWithSideEffects())

You wouldn't expect or want somethingWithSideEffects() to be called when an error is thrown / the method can't possibly be called.

All that to say: first _must_ be called before second:
first().method(second())

@ispacowanguitar some of the time the moments are created in the same millisecond, some of the time not. Nothing to see here.

Was this page helpful?
0 / 5 - 0 ratings