How to create Date on server(there utc timezone) and correct display on client?

965 views Asked by At

We escape of using moment now and use date-fns instead. In some places we still use moment on front. Example of code on server

//date in yyyy/mm/dd format in query params
startOfDay = StartOfDay(new Date(date));
return startOfDay

And when I display this date on front, she changes to local timezone(-4 hours). If i use date-fns-tz and convert to Canada timezone, I will get date with -4 hours and after display -4 hours more. How to resole this issue? I need to add 4 hours to date for my current timeZone. My utcOffset = 4.

1

There are 1 answers

3
Willem Ruys On

Although I am not sure what function your are currently using from date-fns-ts, what has worked for me is to use utcToZonedTime(). This function gets

a date/time in the local time of any time zone from UTC time

import { utcToZonedTime } from 'date-fns-tz'

const now = new Date() // UTC
const nowCustomTimeZone = utcToZonedTime(now, 'Europe/Amsterdam')