skip to Main Content

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


  1. 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".

    console.log(
      new Date('2023-09-04T00:00:00.000Z').toLocaleString('sv',{
        timeZone:'Etc/GMT+2',
        hour12:false,
        timeZoneName:'shortOffset'
      }
    ));

    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).

    Login or Signup to reply.
  2. If you want to achieve what you describe here is one solution which might help you.

    1. convert the string to a Date object

    const time = new Date('2023-09-04T00:00:00.000Z')

    1. subtract the desired minutes

    time.setMinutes(time.getMinutes() - 120) // or however many you might want

    1. revert the subtracted time back into a human readable string

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search