Search code examples
javascripttypescripttimestampmomentjsutc

Comparing a moment.js obect to a timestamp from JSON response


I am trying to compare a moment object (30 days ago) to a given timestamp. Both isBefore and isAfter are returning false. Im not sure where i'm going wrong?

var startdate = moment.utc().subtract(30,'days')

var RequestedDate = moment.utc('14/12/2021, 11:26')

var isbefore = startdate.isBefore(RequestedDate)
var isafter = startdate.isAfter(RequestedDate)

console.log(isafter)
console.log(isbefore)

Solution

  • The requested date is not in the right format, based on the error emitted in a fiddle of your code:

    Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

    If you're able to use the "Date + Format" constructor, then you can parse something like this:

    var RequestedDate = moment.utc('14/12/2021, 11:26', 'D/M/Y, H:m', true)
    // "Tue Dec 14 2021 11:26:00 GMT+0000"
    

    Note the use of strict mode, as in the docs:

    You may get unexpected results when parsing both date and time. The below example may not parse as you expect:

    moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss");