2

I have a dateTime object that I'm using to reflect the status of an item. Below is the code I have for the object:

let status = new Date(Date.parse(dateTime)).toLocaleString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute:'2-digit'}))

Currently status returns, regardless of timezone: 10/19/2022, 10:13 PM

I am in US Central Time. When I console.log

new Date(Date.parse(dateTime))

I get Wed Oct 19 2022 22:13:00 GMT-0500 (Central Daylight Time).

However when I change my computer's time to US Eastern Time, I get: Wed Oct 19 2022 22:13:00 GMT-0400 (Eastern Daylight Time).

This is not correct. I'm expecting Eastern Time to show 11:13 PM or 23:13:00. How should I modify the code to reflect the actual local browser time?

Pointy
  • 405,095
  • 59
  • 585
  • 614
maestro777
  • 161
  • 1
  • 2
  • 17
  • 1
    What exactly is the value of `dateTime`? – Pointy Oct 21 '22 at 13:48
  • The exact value is: `2022-10-19T22:13:17` – maestro777 Oct 21 '22 at 14:13
  • The observed behaviour is exactly as it should be. A timestamp in the format YYYY-MM-DDTHH:mm:ss will be parsed as local. If you want it parsed as a particular offset, then either add the offset to the string before parsing, or use a library and specify the offset or timezone to use when parsing. – RobG Oct 21 '22 at 20:42
  • I want the offset to be automatically detected by the user's location, not manually. For instance, if a user opens my in Dallas, I want them to see central time. Likewise, if a user in New York City opens my page at the exact same time, I want them to see eastern time. – maestro777 Oct 24 '22 at 14:56

1 Answers1

0

I actually figured this out with the help of this demo.

Now my code reads:

let dateTime = '2022-10-19T22:13:17';
let dateInUTC = new Date(Date.parse(dateTime)).toLocaleString() + ' UTC';
let localDate = new Date(dateInUTC);
let status = localDate.toLocaleString('en-US', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit'
});

console.log(status);

If I console.log status, I get 10/19/2022, 05:13 PM. If I change my computer's time zone to Eastern, I get 10/19/2022, 06:13 PM. This is the desired result.

RobG
  • 142,382
  • 31
  • 172
  • 209
maestro777
  • 161
  • 1
  • 2
  • 17
  • 1
    Note that `new Date(dateTime)` is the same as `new Date(Date.parse(dateTime))` – Pointy Oct 21 '22 at 15:49
  • The string produced by *toLocaleString* is implementation dependent and not required to be correctly parsed by the built–in parser. The code in this answer returns an invalid date in Safari and Chrome at least. – RobG Oct 21 '22 at 20:45