0

I need to insert data into my collection with a timestamp reflecting MY timezone, as demonstrated in the code below.

console.log("Testing time: " +new Date(new Date().getTime()+(-7*24*60*60*1000)) )

The code above yields: Testing time: Sat May 29 2021 14:59:14 GMT+0300 (East Africa Time) ...correctly indicating my current timezone!

In order to be able to query my collection based on the various times, I need to format the timestamp by appending .toISOString() to the new Date() function as demonstrated in the code below:

console.log("Testing time: " +new Date(new Date().getTime()+(-7*24*60*60*1000)).toISOString() )

The code above yields: Testing time: 2021-05-29T11:59:08.662Z However NOTE that by appending .toISOString(), the timezone changes.

How do use this format, and STILL maintain my timezone?

SirBT
  • 1,580
  • 5
  • 22
  • 51
  • 1
    The timezone isn't changing, it's just displaying it in ISO format, which includes the `Z` indicating UTC. – Niet the Dark Absol Jun 05 '21 at 12:37
  • You can get ISO format in your required timezone using *toLocaleString* with `new Date('Sat May 29 2021 14:59:14 GMT+0300 (East Africa Time)').toLocaleString('sv',{timeZone:'Africa/Nairobi',timeZoneName:'short'})`, however I think [formatting it manually](https://stackoverflow.com/a/49332027/257182) (a library can help but isn't required) is a far better approach. – RobG Jun 06 '21 at 00:59

1 Answers1

2

Why does adding .toISOString() to my timestamp alter the timezone?

It doesn't, it just produces a string in UTC. It does that because that's how toISOString is specifically defined.

JavaScript's Date object holds the date/time as milliseconds since The Epoch (midnight on January 1st 1970 UTC). It's just that some methods (like toString or getFullYear) interpret that number by applying your local timezone offset, while other methods (like toISOString or getUTCFullYear) stick with UTC.

How do use this format, and STILL maintain my timezone?

By formatting it yourself via getHours, getDate, getTimezoneOffset, String.prototype.padStart, etc. There's no built-in Date method that produces that format in the local timezone.

For example, the date part of it would be:

`${String(dt.getFullYear)}-${String(dt.getMonth() + 1).padStart(2, "0")}-${String(dt.getDate()).padStart(2, "0")}`

getTimezoneOffset gives you the timezone offset from local time to UTC as total minutes (-180 in your case), so you'd divide and remainder it to get the hours and minutes for the GMT+0300 string (that 0300 is HHMM).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875