首页 > 解决方案 > 如何从 JavaScript 中的新日期中减去或添加 GMT 数字?

问题描述

我有 IST 日期和时间 - Thu Oct 01 2020 05:30:00 GMT+0530(印度标准时间),我需要根据用户浏览器时区转换该日期时间。因此,如果我可以从我的日期时间中减去或添加 GMT 值,我可以获得正确的日期时间。请帮忙。

        var newdate = $(this).data("systemdate");
        var format = $(this).data("format");

        var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        var tm_short = moment.tz(newdate, timezone).format('z');

        var datecoverted = new Date(newdate+" GMT+0530")

        var result = moment(datecoverted).format(format); 

我已经尝试使用上面的代码,它在 chrome 中运行良好。但它在 Mozilla Firefox 中显示无效日期。

标签: javascriptdatetime

解决方案


Thu Oct 01 2020 05:30:00 GMT+0530(印度标准时间)格式的时间戳是内置解析器可靠解析的仅有的两个时间戳之一,因此您可以将它们直接传递给 Date 构造函数:

let d = new Date('Thu Oct 01 2020 05:30:00 GMT+0530 (India Standard Time)');

如果时间戳是在客户端系统上生成的,则默认使用系统时区偏移量:

d.toString(); // e.g. Thu Oct 01 2020 09:00:00 GMT+0900 (WIT)

因此,不需要图书馆或任何搞乱时区的东西。

如果你真的想使用一个库,那么你可以在 moment.js 中使用以下代码做同样的事情:

// Timestamp to parse
let s = 'Thu Oct 01 2020 05:30:00 GMT+0530 (India Standard Time)';

// POJS
console.log(new Date(s).toString());

// With moment.js
let format = 'ddd MMM DD YYYY HH:mm:ss ZZ';
console.log(moment(s, format).format(format));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>


推荐阅读