I am getting back UTC time from an API, so in my next project, i am converting the UTC times to the users local time based on a timezone setting coming also from the API.
I am trying to use the isWithinInterval function of date-fns to check if the current time (in that users timezone) is within a start and end time, but it keeps throwing back a
invalid interval
At the top of the file, i am declaring the current time based on timezone;
const nowInUsersTimezone = new Date().toLocaleString('en-AU', { timeZone: user.timezone })
When i console log this, it shows perfect.
When i got to use the isWithinInterval im using the following to check if the nowInUsersTimezone is between 2 dates, if it is, then i just print within, but i cant get it to work;
{
isWithinInterval(
parseISO(nowInUsersTimezone),
{
start: parseISO(formatInTimeZone(job.start_time, user.timezone, 'dd/MM/yyyy, h:mm:ss aaa')),
end: parseISO(formatInTimeZone(job.end_time, user.timezone, 'dd/MM/yyyy, h:mm:ss aaa')),
}
) && (
<>
<p>Within</p>
</>
)
}
console logging the start and end dates works perfect, just when its in the isWithinInterval doesnt work.
Looking at the documentation the
isWithinIntervalfunction fromdate-fnslibrary checks if a date is within a given interval. It expects Date objects as arguments, not ISO strings.The
toLocaleStringmethod returns a string, not a Date object, and the format of this string depends on the locale.I would suggest using
parseISOwith ISO strings. Butnew Date()with a timezone conversion does not return an ISO string. That's likely why you're getting the "Invalid Interval" error.Heres how i would do it:
EDIT: Changed approach
It sounds like the issue is not with the
isWithinIntervalfunction itself, but rather with the comparison of times. The first thing to check is whether the start time is earlier than the end time, and thatnowInUsersTimezoneis in between these two times.