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
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: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.