Szworny Dziąch Szworny Dziąch - 7 months ago 50
Javascript Question

momentjs isBefore returns bad results

I'm trying to check if a given date is before today's date:

const today = moment(new Date(), "YYYY-MM-DD", true);
const isBeforeToday = moment("2016-08-20", "YYYY-MM-DD", true).isBefore(today));

variable has the value of true, which is obviously not correct. Today is 20th of august and 20th of august IS NOT before 20th of august :). Any ideas?


The 20th of Aug isn't before the 20th of August, but:

You're constructing two different kinds of dates: one with time, one without, and midnight is (currently) before the current time.

const today = moment(new Date(), "YYYY-MM-DD", true)
console.log(JSON.stringify(today, null, 2))
// >> "2016-08-20T16:28:23.020Z"

const tmp = moment("2016-08-20", "YYYY-MM-DD", true)
console.log(JSON.stringify(tmp, null, 2));
// >> "2016-08-20T04:00:00.000Z"

const isBeforeToday = tmp.isBefore(today)
// >> true

You're constructing your first moment with a Date, not a string; there's nothing to parse. Thus your moment has all the date fields. If you created your Date object without time fields you get what you expect:

const today2 = moment(new Date(2016, 07, 20), "YYYY-MM-DD", true)
console.log(JSON.stringify(today2, null, 2))
// >> "2016-08-20T04:00:00.000Z"

const tmp2 = moment("2016-08-20", "YYYY-MM-DD", true)
console.log(JSON.stringify(tmp2, null, 2));
// >> "2016-08-20T04:00:00.000Z"

const isBeforeToday2 = tmp2.isBefore(today2)
// >> false