3

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Gooby
  • 621
  • 2
  • 11
  • 32
  • 1
    Could you please clarify which portion is a problem - converting ISO8601 to .Net `DateTime`, figuring client's timezone on server, converting ISO8601 to local time in browser? (@DiogoRocha suggested a duplicate but while it is exactly what post is asking it will unlikely help you as you can't know client's timezone on server) – Alexei Levenkov Mar 19 '19 at 17:43

2 Answers2

9

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
1

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.

Community
  • 1
  • 1
matri70boss
  • 349
  • 2
  • 13