Javascript date difference is off by one for some dates

Viewed 33

I have had issues with time zones and UTC dates in the past but its unclear why my date difference in variable TotalDays is off by 1 for some dates and not for others.

For example dates : 2022-07-01T00:00:00 to 2023-06-30T00:00:00 returns 364 days instead of 365 despite it is a full year. However, 2022-05-02T00:00:00 to 2022-05-11T00:00:00 returns 9 days.

My code is as follows:

            dateFormat(date1, date2) {
                startDate = new Date(date1)
                endDate = new Date(date2)

                let TotalDays = (endDate - startDate)/ (1000 * 3600 * 24);
                alert(TotalDays)
                if (TotalDays != 365 || TotalDays != 366)
                {
                    //this date is not on a full calendar year or fiscal year
                    return dayjs(startDate).format('MMM YYYY') + ' - ' + dayjs(endDate).format('MMM YYYY')
                } else {

                    if (startDate.getUTCMonth == 0 && StartDate.getUTCDate == 1)
                    {
                        //this is January start date
                        return 'CY' +  dayjs(endDate).format('YYYY')
                    } else if (startDate.getUTCMonth == 6 && startDate.getUTCDate == 1) {
                        //this is July start date
                        return 'FY' + dayjs(endDate).format('YYYY')
                    } else {
                        //not a true FY or CY so default to RY
                        return 'RY' + dayjs(endDate).format('YYYY')
                    }
                }

            }
0 Answers
Related