Home > database >  Updating to v2 date-fns: NaN
Updating to v2 date-fns: NaN

Time:07-22

I'm updating the module date-fns from v1 to v2.

This helper method used to work:

const { format, parseISO, differenceInSeconds } = require("date-fns");

const newDateNow = () => {
    const date = new Date();
    return format(date, process.env.DATE_FORMAT);
};

// `process.env.DATE_FORMAT` is set to `yyyy-MM-dd HH:mm:ss`
console.log(ff) //prints: Thu Jul 21 2022 14:44:56 GMT 0200 (Central European Summer Time)
console.log(gg) //prints: 3600
console.log(newDateNow()) //prints: 2022-07-21 15:32:05

const isExpired = () => {
    const exp = differenceInSeconds(newDateNow(), ff);
    return parseInt(gg) > exp;
}

After the update to the module's v2 this generates the error: date-fns doesn't accept strings as date arguments. Please use 'parseISO' to parse strings. This pointing to the const exp line.

So I change that line to:

const exp = differenceInSeconds(newDateNow(), parseISO(ff));

This still generates the same error, so I change it to:

const exp = differenceInSeconds(parseISO(newDateNow()), parseISO(ff));

Now there is no error, but console.log(exp) prints NaN.

How should I implement this? Shouldn't I change the newDateNow method so that it's not necessary to use parseISO() on newDateNow()?

CodePudding user response:

differenceInSeconds() is a function which takes two Date objects as arguments. In your code, newDateNow() is returning a string because you’re calling format() on the date, so you’re passing it a string rather than a date.

So based on just needing to compare the two dates you should skip that call to format() entirely.

Your code sample doesn’t include the assignment of ff, you will need to ensure that is a date and not a string as well.

If you haven't seen already, the documentation is handy: https://date-fns.org/v2.28.0/docs/Getting-Started

  • Related