javascript - 在 HTML 中将 UTC 日期转换为本地日期的简洁方法

标签 javascript html date

服务器呈现一个带有完整 UTC 日期/时间的网页:

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

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

我正在寻找一种干净的方法来在本地(客户端)时区显示此日期/时间。这按预期工作,但代码太多:

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

是否有某种方法或库可以允许执行类似的操作?

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

最佳答案

以下内容可能会帮助您入门。

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.

关于javascript - 在 HTML 中将 UTC 日期转换为本地日期的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48906106/

相关文章:

javascript - innerHTML 在 if/else 中不起作用

javascript - 禁用 HTML5 视频标签上的全屏按钮

html - 如何使此 HTML 更改生效?

java - 如何在 CSV 导出期间保留日期格式

javascript - 使用 Electron Build 捆绑 MSI 安装程序

javascript - 无法向 js 对象添加属性

javascript - 模块 MySQL Nodejs

jquery - 我的博客有一个 jquery 评论插件,但我不知道评论存储在哪里?

mysql - 具有唯一 ID 的高级平均日期差异

java - 如何判断 Java 日期和时区是否早于当前时间?