0

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

我现在需要做的是创建一个带有选定日期、选定时间和特定时区的 JS 日期对象。
我正在尝试使用时刻(因为我们将它用于整个应用程序中的日期),但我没有预期的行为。

我试着:

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是返回我当前的时区事件,尽管它在时刻对象中出现了我的不同时区。 在此处输入图像描述

为什么它会这样工作,什么是我需要的工作实现?

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

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

谢谢。

4

1 回答 1

0

看起来您尚未使用有关要使用的时区的任何数据设置 moment-timezone。在 momentjs 中查看有关数据加载的链接。

我为您的示例创建了一个 JS Bin,它展示了如何使用数据加载。在这里查看。例如

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'
]);
于 2018-12-20T19:34:50.320 回答