I am having the following zulu time
2023-09-04T00:00:00.000Z
this date is given as output from some library so I know that it is UTC time.
When the library gives that output I need to transform this timestamp time to my local time – because I know that my time is -120 minutes from the UTC the final output should be 2023-09-04T22:00:00.000Z
.
Or let’s say that the library gives me this output 2023-09-10T23:59:59.590Z
, I should convert it to 2023-09-10T21:59:59.590Z
.
So I tried first to find out the timezone offset in minutes according to the local timezone of the user.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_gettimezoneoffset
In my case as I said it is -120 minutes. I can’t find a way how can I minus this 120 minutes of my initial timestamp and construct new timestamp.
2
Answers
The simplest way is to use toLocaleString with an appropriate language and offset.
E.g. the following produces "2023-09-03 22:00:00 GMT−2".
The Etc offsets use the POSIX sense, so +2 is equivalent to GMT-2.
Note that toLocaleString is not that reliable for formatting, better to use a library or your own formatting function (which might start with toLocaleString or Intl.DateTimeFormat to get the parts).
If you want to achieve what you describe here is one solution which might help you.
const time = new Date('2023-09-04T00:00:00.000Z')
time.setMinutes(time.getMinutes() - 120) // or however many you might want
const newTime = time.toISOString() // would print: 2023-09-03T22:00:00.000Z
As other have mentioned already, this might not the best practice. You can write a function which can give you the correct datetime based on the locale (whether that would be from the browser or given as a parameter), or implement an already existing library which can do that for you.