React - differenceInDays in date-fns returning NaN

31 Views Asked by At

Im trying to get the difference in days between the current date, and a products expiry date in the users timezone, but keep getting a NaN error and cant figure out why. My code looks like;

import { formatInTimeZone } from 'date-fns-tz'
import { differenceInDays } from 'date-fns'

const DifferenceInDays = ({ target, user }) => {
    const expiryDate = formatInTimeZone(new Date(target.expiry_date), user.timezone, "dd/MM/yyyy");
    const currentDate = formatInTimeZone(new Date(), user.timezone, "dd/MM/yyyy");

    const daysDifference = differenceInDays(
        new Date(expiryDate),
        new Date(currentDate)
    )

    return (
        <>
            {daysDifference}
        </>
    )
}

export default DifferenceInDays

If i log the expiryDate and currentDate they both return valid, its just when trying to get the difference in days

1

There are 1 best solutions below

0
On

You will need to make sure that expiry_date is a valid date. If so, then you should be able to subtract it from the current date and convert the result into days, like here:

let target = {
    expiry_date: new Date('2000-01-01 10:00:00'),
};

console.log(Math.round((new Date() - target.expiry_date) / (1000 * 3600 * 24)));

It makes little sense to convert your dates into formatted strings, then to convert them back to dates and subtract them.

Instead, have your date values and use computation between actual, nonconverted dates and store formatted strings in separate variables.