gpt4 book ai didi

javascript - moment.js 正在更改时区的输入时间,而它本来就应该是该时区

转载 作者:行者123 更新时间:2023-11-27 23:10:02 24 4
gpt4 key购买 nike

所以我尝试使用 moment.js 进行一些时间转换,为了清楚起见,我使用 Angular 进行一些数据绑定(bind)

$scope.resolveTime = function () {

var m = moment.tz($scope.inputTime, 'America/Los_Angeles');
$scope.inputTime = m;
var zone = jstz.determine();

$scope.outputTime = m.tz(zone.name()); // Convert CDT to local time

console.log("inputtime: " + $scope.inputTime.format())
console.log("local: " + $scope.outputTime.format())
};

我认为这很简单,但我猜正在发生的是,当我传递 inputTime 并告诉时刻它是 America/Los_Angeles 时,它会将当前本地时间转换为 PDT,而不是设置它到 PDT,因为下面的代码将其转换回本地时区,从而导致两个变量的数字完全相同。有人知道解决这个问题的方法吗?结果应该是用户输入一个时间(以 PDT 形式),它将显示用户本地时间的时间。

更新:经过更多研究后,我认为这实际上是我的时间选择器将输入更改为本地的 Date 对象,我使用的时间选择器是 Angular Ui Boostrap 以供引用

最佳答案

这可以变得更容易一些。

首先,时刻是可变的。这就是为什么 $scope.inputTime$scope.outputTime 具有相同的值。您可以使用 .clone() 克隆 Moment 来修复此问题。

此外,要将日期转换为用户的本地时间,您可以仅依靠浏览器内置的行为以及 moment 的 .local() 函数。除非您确实想知道他们的时区,否则不需要去 jstz 获取用户的本地时间。

值得注意的是,自 0.5.0(2015 年 12 月)起,Moment Timezone 内置了 jstz 通过 moment.tz.guess() 提供的功能。

将它们放在一起,您的代码应如下所示:

function () {

var m = moment.tz($scope.inputTime, 'America/Los_Angeles');
$scope.inputTime = m;

$scope.outputTime = m.clone().local(); // Convert CDT to local time

console.log("inputtime: " + $scope.inputTime.format())
console.log("local: " + $scope.outputTime.format())
};

关于javascript - moment.js 正在更改时区的输入时间,而它本来就应该是该时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com