服务器呈现一个带有完整 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/