0

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>

Pavel Tupitsyn
  • 8,393
  • 3
  • 22
  • 44
  • 1
    Have a look at moment.js https://momentjs.com/ – Stretch0 Feb 21 '18 at 12:36
  • Print an UNIX timestamp instead and parse it : https://stackoverflow.com/a/847196/2116001 – gogaz Feb 21 '18 at 12:37
  • I'm not talking about formatting the date, I can do that. The question is about making this code concise and getting rid of inline JS. – Pavel Tupitsyn Feb 21 '18 at 12:41
  • The timestamp doesn't have a time zone, so will be treated as "local" everywhere and will represent a different instant in time in each host with a different offset. – RobG Feb 21 '18 at 20:52

1 Answers1

4

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.

Community
  • 1
  • 1
Keith
  • 22,005
  • 2
  • 27
  • 44
  • Please don't suggest using the built-in parser, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) An ISO 8601 format string without timezone should be parsed as local, but some browsers will parse it as UTC. Strings should always be manually parsed, with a bespoke function or library. – RobG Feb 21 '18 at 20:54
  • @RobG Your correct, dates in JS can be problematic. Just wanted to keep snippet as simple as possible,. I'll add a note in answer. – Keith Feb 22 '18 at 10:08
  • 1
    Thanks. I had to append "Z" to the date string before parsing so that it would parse as utc. – Luke Chinworth Jun 11 '20 at 21:27
  • @LukeChinworth Good point!, some browsers might be very strict on the date constructor. I've added a Z to the snippet,. – Keith Jun 12 '20 at 14:41