Pavel Tupitsyn
Pavel Tupitsyn

Reputation: 8986

Clean way to convert UTC date to local in HTML

Server renders a web page with a full UTC date/time on it:

<span>@Model.RunDate.ToString("o")</span> ->

<span>2018-02-20T17:54:26.5685810</span>

I'm looking for a clean way to display this date/time in a local (client-side) time zone. This works as intended but is too much code:

<span>
    <script type="text/javascript">
        document.write(new Date("@Model.RunDate.ToString("o")"));
    </script>
</span>

Is there some approach or a library which will allow to do something like this?

<span class="utcToLocal">2018-02-20T17:54:26.5685810</span>

Upvotes: 0

Views: 1219

Answers (1)

Keith
Keith

Reputation: 24181

Below is something that might get your started.

document.querySelectorAll(".utcToLocal").forEach(
  function (i) {
    i.innerText = new Date(i.innerText).toLocaleString();
  }
);
<span class="utcToLocal">2018-02-20T17:54:26.5685810Z</span>

Please note, as @RobG mentions dates in JS can be problematic, and instead of just using the built in Date.parse, it is adviced to either parse the date manually, or use some good third party library. https://momentjs.com/ is a popular choice.

Also as pointed out in comments, some browser could be very strict on the date constructor as such it's also a good idea to add a Z to the end of the time to let the browser know it's an ISO time.

Upvotes: 4

Related Questions