jojojohn
jojojohn

Reputation: 753

Check if date is within the next three months with moment

What I have always returns true:

const dateToCheck = '2020-02-18 11:46:04'  
const isInNext3Months = (dateToCheck) => {
    return moment().diff(dateToCheck, "days") < 30
}

Not sure why

Upvotes: 1

Views: 1867

Answers (1)

JS Lover
JS Lover

Reputation: 622

const afterThreeMonths = '2020-05-18 11:46:04'  
const beforeTreeMonths = '2020-02-18 11:46:04'  
const isInNext3Months = (dateToCheck) => {
    return moment().diff(dateToCheck, "days") > -90
}

console.log(isInNext3Months(afterThreeMonths)) // false
console.log(isInNext3Months(beforeTreeMonths)) // true

Diff returns a negative value, so you need to flip your comparison, also three months is 90 days and not 30 days as specified in your function.

And hard coding the number of days is not the correct way to go about it, because you don't know if the coming month is 30 or 31 days.

You would need to do something like this How to get list of days for last month, last three months in MomentJS but to check for the coming months.

Upvotes: 1

Related Questions