更改时刻时区不反映到.toDate()

时间:2018-12-20 16:23:12

标签: javascript date timezone momentjs moment-timezone

Ngx Bootstrap Datepicker返回一个JS Date对象。
我有一个自定义的时间选择器,它返回格式为HH:mm的字符串。

我现在需要做的是使用选定的日期,选定的时间和特定的TimeZone创建一个JS Date对象。
我正在尝试使用力矩(因为我们在整个应用程序中都将其用于日期),但是我没有期望的行为。

我正在尝试:

const specificMoment = moment.tz(date, timeZone); // date is the Ngx Bootstrap selected date
specificMoment.set('hour', +time.split(':')[0]); // time is HH:mm string
specificMoment.set('minute', +time.split(':')[1]);
return specificMoment.toDate

* {timeZone根据用户而变化,不是由于它的浏览器,而是用户的属性,因此我无法设置moment.tz.setDefault(...);

我要面对的是.toDate返回我当前的timeZone事件,尽管它在moment对象中出现了我不同的timeZone。 enter image description here

为什么这样工作,而对于我所需要的却是可行的实现方式?

Ps:console.log(specificMoment.format());也会返回错误的timeZone 2018-12-20T23:00:30-02:00

编辑
依次使用
const specificMoment = moment(date).tz(timeZone);
return specificMoment.toDate()
“工作”。它返回带有2018-12-21T05:00:00.323-0200的Date对象,该对象是具有指定时区(GMT -8:00)的日期,但显示在我当前的时区(GMT -2:00)上。
数据已正确存储在我的数据库中。
有人可以解释为什么吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您似乎尚未使用要使用的时区的任何数据来设置moment-timezone。 在momentjs的Data Loading上查看此链接。

我为您的示例创建了一个JS Bin,该示例展示了如何使用数据加载。签出here。 例如

moment.tz.add([
    'America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0',
    'America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0'
]);