在我的用户界面上,我尝试根据特定时区显示日期。在此示例中,我将使用 Americas/New_York 作为时区。我就是这样做的。
$scope.getStartTime = function(){
var date = new Date();
return moment(date).tz("Americas/New_York").format('YYYY-MM-DD HH:mm:ss');
};
然后,我想发送此数据并将其发送到我的服务器。然而,在我的服务器中,我希望它始终序列化为 UTC 时间,而不是纽约时区 (EST)。
例如,如果时间是中午 12:00如果在纽约,则时间将连载至下午 4:00。发送到后端之前的 UTC 时间。这是我的尝试:
var date = getStartTime();
....
// Display the date in the UI
....
$scope.revertStartTime(date);
$scope.revertStartTime = function(startTime) {
console.log("Start time: ", startTime);
console.log("Moment: ", moment(startTime).format());
console.log("Converted to utc time: ", moment().utc(startTime).format());
return moment.utc(startTime).format("YYYY-MM-DD'T'HH:mm:ss.SSSZ");
}
我尝试使用 moment().utc()
函数恢复开始时间,并希望日期将更改为基于 UTC 的日期,但不幸的是它不断将我的日期变成本地化日期日期而不是 UTC 日期,我不知道为什么。任何帮助,将不胜感激。谢谢!
编辑:
尝试遵循以下方法,这就是我所做的:
$scope.getStartTime = function(){
var date = new Date();
var startTime = new moment(date).tz($rootScope.userinfo.timeZone).format('YYYY-MM-DD HH:mm:ss');
$rootScope.offset = moment().utcOffset(startTime);
console.log("offset: ", $rootScope.offset);
return startTime;
};
$scope.revertStartTime = function(startTime) {
console.log("User Selected Time: ", moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss'));
return moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss');
}
但我得到的只是一个错误,指出 revertStartTime
返回一个无效日期
。
最佳答案
一些事情:
希望这是一个拼写错误,但需要指出的是,区域 ID 是
<America/New_York
,而不是Americas/New_York
。您可以将值传递为
moment.utc(foo)
或moment(foo).utc()
,但不能传递moment( ).utc(foo)
。区别在于,一个将输入解释为 UTC 并保持 UTC 模式,而另一个只是切换到 UTC 模式。您也可以将其视为“转换为 UTC”,但实际上底层时间戳值不会改变。是的,您可以切换到 UTC 模式和调用格式,但无论您处于哪种模式,您也可以只调用
.toISOString()
。这已经是 ISO 格式了您正在寻找。请注意,如果您从一个唯一的时间点开始,并以转换为 UTC 结束,那么中间的任何时区切换或偏移量都不会改变结果。换句话说,这些都是等价的:
moment().toISOString() moment.utc().toISOString() moment(new Date()).toISOString() moment.utc(new Date()).toISOString() moment(new Date()).utc().toISOString() moment().tz('America/New_York').toISOString() moment.tz('America/New_York').toISOString() moment().utcOffset(1234).toISOString() moment.utc().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]') moment().utc().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]')
只有最后两个需要处于 UTC 模式,因为如果处于本地模式或特定时区,
format
函数会产生不同的输出。
关于javascript - 将时区格式的日期显示为 UTC 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36630569/