Search code examples
javascriptdatereact-reduxtimezonedate-fns

Timezone independent dates javascript


Using javascript/react native + redux i need to save timestamps in a time format that is aware of local time when saving the date, but unaware when reading the same date in another timezone.

Take a hypothetical user that travels west around the world in one day, saving a time stamp every hour, all i different timezones, all at 2021-01-30 at 18:00 hours local time. Resulting in 24 timestamps at 18:00.

Using a function in the likes of isWithinInterval from date-fns in a similar fashion as below, all timestamps should return true.

isWithinInterval(
  timestamp,
  {start: new Date(2021,0,30,17,30}, end: new Date(2021,0,30,18,30)}, 
) // -> true

How do one go about doing this? Preferrably in a react-redux compatiable (serializable) way. By default, your date object will be saved in UTC based on the local time on your device.


Solution

  • I had such a hard time to wrap my head around the date objects that it took a long time for me to understand that this problem is actually what "date-fns-tz" package is all about. This is how i'm currently solving it:

    1. Create a utc-time identical to the local time using:
    import {zonedTimeToUtc} from "date-fns-tz"
    const myDate = new Date()  // eg 2021-02-03 10:00 UTC +5
    const localTimeIdenticalUtc = zonedTimeToUtc(localDateObject, localTimeZone)  // 2021-02-03 10:00 UTC +-0
    
    1. When i want to use the UTC-date, i transfer it back to an identical localDate for whatever time zone i am in.
        import {utcToZonedTime } from "date-fns-tz"
        const zonedTimeToUtc(localTimeIdenticalUtc, localTimeZone) // 2021-02-03 10:00 UTC +5