0

I have a function as follows it takes in a date and checks whether the given date is in last month or not.

const { 
subMonths, 
getMonth, 
lastDayOfMonth, 
startOfMonth, 
isWithinInterval 
} = require('date-fns')

function isLastMonth(date) {

    let lastMonthDateOfGivenDate = subMonths(new Date(date), 1)

    let today = Date.now()
    let lastMonthDate = subMonths(today, 1);

    let firstDayOfLastMonth = startOfMonth(lastMonthDate)
    let lastDayOfLastMonth = lastDayOfMonth(lastMonthDate)

    if (isWithinInterval(lastMonthDateOfGivenDate, { start: firstDayOfLastMonth, end: lastDayOfLastMonth }))
        console.log("true")
    else
        console.log('false')

}

isLastMonth("2020-03-30T15:24:02.647Z")

The problem is is I'm not able to check for dates which have 31 days or 30 days for february.

Any solution or other approach for this problem? Thank you.

  • Maybe this can help, if you didn't saw this answers already: [how-to-validate-date-if-is-the-last-day-of-the-month-with-javascript](https://stackoverflow.com/questions/6355063/how-to-validate-date-if-is-the-last-day-of-the-month-with-javascript) – Mara Black Mar 30 '20 at 06:59

1 Answers1

1

The solution is as follows

import {subMonths, startOfMonth, endOfMonth, isWithinInterval} from 'date-fns'

function isLastMonth(date) {

    let today = Date.now()
    let lastMonthDate = subMonths(today, 1);

    let firstDayOfLastMonth = startOfMonth(lastMonthDate)
    let lastDayOfLastMonth = endOfMonth(lastMonthDate)

    return isWithinInterval(new Date(date), { start: firstDayOfLastMonth, end: lastDayOfLastMonth })

}

All the edge cases will be handled by javascript itself; for example, the previous month date of May 31, 2020, will be April 30 2020.