How to stop conversion of the timezone on new date object in javascript lwc?

1.1k views Asked by At

I receive a datetime string with different timezones (for example '2020-10-28T08:00:00+10:00, 2020-10-28T11:00:00+11:00'). When I create new date object, it converts the string to the current User timezone, displaying different date and time on UI rather than showing what is being received. How to stop timezone conversion?

1

There are 1 answers

1
Matt Johnson-Pint On

If LWC uses the JavaScript Date object, then sorry - but there's nothing you can do. The behavior you described is how the Date object works.

The Date object internally tracks only a timestamp which is the number of milliseconds since the Unix epoch: 1970-01-01T00:00:00.000Z (UTC). If you parse a string with an offset, that offset is considered when determining the timestamp. If you create a string with toString(), it uses the system local time zone to convert the timestamp to a string. The original string you parsed, or its offset, is not retained in the Date object.

I don't know much about LWC, but in general you can only solve this by not using a Date object, and using something else instead. There are many good JavaScript date libraries to pick from, such as Luxon.