'How to guess user's timezone using date-fns?

I have a requirement, where I need to show a user's time in their local time zone. This needs to be done using date-fns.

The following code checks the current time and then given a timezone converts it into local time as per the time zone.

const { formatToTimeZone } = require('date-fns-timezone')

let date = new Date()
const format = 'D.M.YYYY HH:mm:ss [GMT]Z (z)'
const output = formatToTimeZone(date, format, { timeZone: 'Asia/Calcutta' })

However, how do I guess the user's timezone on the fly?

In moment.js, you can get it with moment.tz.guess(). But how can I do it without moment.js and by using date-fns?

https://runkit.com/embed/835tsn9a87so

UPDATE: I will be using this inside a VueJS application. So, if there are any other related solutions, those are welcomed as well. Thanks.



Solution 1:[1]

Just solved a similar problem myself. The trick is to use the format function from date-fns-tz instead of the one from date-fns.

import { format } from "date-fns";
console.log(format(new Date(), "yyyy-MM-dd HH:mm z"));
// 2021-11-29 13:55 GMT-8

import { format } from "date-fns-tz";
console.log(format(new Date(), "yyyy-MM-dd HH:mm z"));
// 2021-11-29 13:55 PST

See documentation here: https://date-fns.org/v2.27.0/docs/Time-Zones

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben Harris