MomentJS和时区/UTC计算 [英] MomentJS and timezone/UTC calculations

查看:940
本文介绍了MomentJS和时区/UTC计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自API的JavaScript date对象;但是当我使用Moment进行一些日期操作时,时区组件被弄乱了,现在的日期现在使用GMT当地时间:

I have a JavaScript date object which has come from an API; but when I use Moment to do some date manipulation, the timezone component is messed up and the resulting date now uses GMT local time:

var d = new Date("2018-09-30T00:00:00+10:00");
var m1 = moment(d).toDate(); // 2018-09-29T14:00:000Z
var m2 = moment.utc(d).toDate(); // 2018-09-29T14:00:000Z

如何保存我的时区信息,以便当我开始添加天数/小时数等时,结果值仍保留在+10:00时区中?

How do I preserve my timezone information so that when I start adding days/hours etc, the resulting value remains in the +10:00 timezone?

如果我查看在例如Firefox调试器,我可以看到m1具有_tzm:600_isUTC:false,而m2具有_tzm:600_isUTC:true,但是在两种情况下,包装的_d2018-09-29T14:00:000Z而不是2018-09-30T00:00:00+10:00如我所愿.

If I look at the moment object created in e.g. Firefox debugger, I can see that m1 has _tzm:600 and _isUTC:false, whereas m2 has _tzm:600 and _isUTC:true but in both cases, the wrapped _d is 2018-09-29T14:00:000Z and not 2018-09-30T00:00:00+10:00 as I would hope.

如果我打电话:

var m3 = moment(d).format(); // 2018-09-03T00:00:00+10:00

那一切都还好,但是现在我有了string而不是Date对象

then everything is okay, but now I have a string rather than a Date object

推荐答案

通过定义,Date对象仅使用UTC:

By definition, Date objects are just in UTC:

创建一个JavaScript Date实例,该实例表示一个时刻 时间.日期对象基于时间值,该时间值是 自1970年1月1日UTC以来的毫秒数.

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC.

不过,浏览器通常会将其转换为本地时间.

The browser usually will transform this to local time, though.

我不确定您要完成什么.但是,通常,要在不同时区中打印回日期,可以使用字符串.至于时区操作,时刻时区可能是您的理想选择.

I am unsure what you are trying to accomplish. However, in general, for printing back the date in a different timezone, string would be the way. As for timezone manipulation, Moment Timezone might be your place to go.

话虽如此,如果您的用例很简单,则可以尝试直接解析字符串日期时刻并使用parseZone.它将允许您捕获确切的日期并获取时区信息.

That being said, if your use case is simple, you can try directly parsing the string date moment and using parseZone. It will allow you to capture the exact date and get timezone information as well.

只显示一个小片段.

const date = '2018-09-30T00:00:00+10:00';

const parseZone = moment.parseZone(date);
console.log('Original time: ', parseZone.format());

const offsetTimezone = parseZone.format('Z');
console.log('Timezone', offsetTimezone);

const utcOffset = parseZone.utcOffset();
console.log('Offset from UTC in minutes', utcOffset);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

这篇关于MomentJS和时区/UTC计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆