Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Convert ISO8601 UTC time to client's local time [duplicate]

I'm using asp.net mvc 5 for my website and I'm sending the date of a transaction as a DateTime object from the model to the view in UTC using ISO8601 format- 2019-03-15T22:32:04.9143842Z.

If I receive 2019-03-15T22:32:04.9143842Z as a string from the model I need a function that can convert it to local time for the client. So if the client is in PST then it should convert it to such.

like image 468
Gooby Avatar asked May 31 '26 17:05

Gooby


2 Answers

You can simply pass this format to the Date object constructor (or to Date.parse).

var d = new Date("2019-03-15T22:32:04.9143842Z");

The Z on the end is critical, as it indicates UTC.

You can then use functions like .toString() or .toLocaleString() that emit local time. You can find the Date object reference on MDN here.

When run in the US Pacific time zone:

console.log(d.toString());
//=> "Fri Mar 15 2019 15:32:04 GMT-0700 (Pacific Daylight Time)"

Alternatively, you can use a library such as Date-fns, Luxon, or Moment to format your date to a string in a specific way.

like image 200
Matt Johnson-Pint Avatar answered Jun 03 '26 05:06

Matt Johnson-Pint


This datetime type / standard is iso 8601 . https://en.wikipedia.org/wiki/ISO_8601 There are lot of different types of possibilities how to parse iso 8601 date with javascript, one of them being

new Date(isoDateString)

other including packages such as https://github.com/datejs/Datejs (Date.parse(isoDateString)) or manually parsing it yourself.
Then you can get the clients timezone and change the timezone to it / or any desired timezone.

like image 41
matri70boss Avatar answered Jun 03 '26 07:06

matri70boss