简体   繁体   English

在 HTML 中将 UTC 日期转换为本地的干净方法

[英]Clean way to convert UTC date to local in HTML

Server renders a web page with a full UTC date/time on it:服务器呈现一个带有完整 UTC 日期/时间的网页:

<span>@Model.RunDate.ToString("o")</span> -> <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>

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.请注意,由于@RobG 提到 JS 中的日期可能有问题,而不是仅使用内置的 Date.parse,建议手动解析日期,或使用一些好的第三方库。 https://momentjs.com/ is a popular choice. https://momentjs.com/是一个流行的选择。

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.同样如评论中指出的那样,某些浏览器可能对日期构造函数非常严格,因此在时间末尾添加Z以让浏览器知道这是 ISO 时间也是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM