javascript - 如何从 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 中显示无效日期。
解决方案
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>
推荐阅读
- javascript - 多个单独的浏览器,每个浏览器都有一个选项卡 - 与页面上的元素同时交互(木偶无头)
- angular - 如何在 Angular 9 ReactiveForm 中获取嵌套的 FormArray 控件
- flutter - 应用程序启动时如何打开抽屉?
- .net - 每次我向 Web API 发送请求时,.net 核心会创建一个新会话吗?
- python - 在 TKinter 的列表框中显示某些信息
- excel - 根据列中的字符串有条件地折叠 Excel 行?
- python - 如何使用决策树获得拟合值?
- javascript - 如何在 javascript 中提醒 URL 排除 filename.php?
- python - 尝试加载“rest_framework.templatetags.rest_framework”时引发 ImportError:无法从“django.utils”导入名称“six”
- javascript - 动态禁用反应形式的下拉菜单