【问题标题】:How to get date to ISOString with GMT timezone如何使用 GMT 时区获取 ISO 字符串的日期
【发布时间】:2020-04-07 12:29:00
【问题描述】:

我得到日期

Fri Dec 20 2019 00:00:00 GMT+0600 (East Kazakhstan Time) 

但是当我转换为 ISOString 时,我得到了

2019-12-19T18:00:00.000Z

我猜这个转换不考虑时区..

我也尝试使用时刻时区和相同的结果进行转换。

moment("Fri Dec 20 2019 00:00:00 GMT+0600 (East Kazakhstan Time)").tz('Asia/Bishkek').toISOString()  


如果我得到 date with timezone 我应该 convert with timezone
应该得到

2019-12-20T00:00:00.000Z

不是

2019-12-19T18:00:00.000Z

如果我错了,请纠正我


更新

我找到了解决我的问题的解决方案

moment(this.data.start.getTime() - this.data.start.getTimezoneOffset()*60*1000).toISOString()

从 GMT +0 转换为 GMT +6 时区
现在新问题:
如何使用momentjs使上面的代码更简单..或者这样就足够了?

【问题讨论】:

  • 这会将日期更改为比应有的时间晚 6 小时,即您从根本上更改了日期所代表的时间。

标签: javascript typescript date momentjs toisostring


【解决方案1】:

我得到日期 Fri Dec 20 2019 00:00:00 GMT+0600(东哈萨克斯坦时间)但是当我转换为 ISOString 时,我得到 2019-12-19T18:00:00.000Z

时间戳代表完全相同的时刻。这里没有错误。

如果我得到带有时区的日期,我应该使用时区进行转换。我应该得到 2019-12-20T00:00:00.000Z

不,你不应该。你应该得到 2019-12-19T18:00:00.000Z。

如果我错了,请纠正我

你说的不对。

toISOString 始终为 UTC。如果您想要 ISO 8601 格式和本地时区,请使用内置解析器和默认的 moment 格式:

let s = 'Fri Dec 20 2019 00:00:00 GMT+0600 (East Kazakhstan Time)';

// Built–in parser, not recommended
let d = new Date(s);
// Format with moment.js
console.log(moment(d).format());

// Modify string for parsing with moment.js
let e = s.substr(0,33).replace('GMT','');
// Parse with moment.js
let m = moment(e, 'ddd MMM DD YYYY HH:mm:ss ZZ');
// Format with moment.js
console.log(m.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 2021-03-12
    • 1970-01-01
    • 2018-02-04
    • 2014-05-09
    • 2012-04-17
    • 2020-12-15
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多