I work for a French company and, with our marine territories, our customers live in many timezones. So I’m wondering what is, in 2022, the correct way to display dates in browser timezone with Phoenix?
The reason to do it in JS is that the server doesn’t know or need to know the timezone. If the server is already aware of the users timezone however you can surely handle that in elixir as well.
If You use liveview, You can set timezone, timezone_offset in the live socket, this way You can retrieve this information server side, and do the translation in the server.
let liveSocket = new LiveSocket("/live", Socket, {
hooks: Hooks,
params: {
_csrf_token: csrfToken,
locale: Intl.NumberFormat().resolvedOptions().locale,
// timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
// USE POLYFILL FOR IE11
timezone: moment.tz.guess(),
timezone_offset: -(new Date().getTimezoneOffset() / 60),
}
});
But as other have also mentionned, I prefer to do it client side
not sure it would help you, but below JavaScript code results in producing the date and time in user’s time zone… just give it a try in the browser’s console tab.
This is what I do. Admittedly, it felt a little strange at first, but since Liveview is mostly replacing javascript in my app, it made sense to bring knowledge of the user’s timezone to the Elixir side. I’m also doing a lot more with calendaring than just displaying the user’s time though. If my needs were simple enough, I’d probably still just stick with displaying via javascript.
I too think that whatever timezone you think the user wants dates/times displayed in, give them an option to tell you what they want. Assuming browser timezone, or timezone based on IP address or locale or some other automated mechanism can create a worse experience. Let say I’m living in Singapore but travelling in the US and trying to schedule a meeting for when I get back. I don’t want dates/times to be rendered based upon where I am, but based upon where I’m going.