Zou*_*air 33 timezone date momentjs
我的问题是如何在不同的时区获得相同的日,月,年,小时,分钟,秒,例如:
var now = moment().valueOf();
var result1 = moment(now).format('DD-MM-YYYY HH:mm:SS Z');
Run Code Online (Sandbox Code Playgroud)
在我的时区,我得到这样的一些:
18-02-2015 21:08:34 +01:00
Run Code Online (Sandbox Code Playgroud)
那么如何在不更改其他值(天,月,......,分钟......)的情况下仅更改时区
我想得到这样的东西:
result2: 18-02-2015 21:08:34 +01:00
result3: 18-02-2015 21:08:34 +10:00
result4: 18-02-2015 21:08:34 +05:00
result5: 18-02-2015 21:08:34 -06:00
result6: 18-02-2015 21:08:34 -11:00
Run Code Online (Sandbox Code Playgroud)
提前致谢
Mat*_*int 57
以下是您可以按照自己的要求做的事情:
// get a moment representing the current time
var now = moment();
// create a new moment based on the original one
var another = now.clone();
// change the offset of the new moment - passing true to keep the local time
another.utcOffset('+05:30', true);
// log the output
console.log(now.format()); // "2016-01-15T11:58:07-08:00"
console.log(another.format()); // "2016-01-15T11:58:07+05:30"
Run Code Online (Sandbox Code Playgroud)
但是,您必须认识到两件重要的事情:
该another
对象不再代表当前时间 - 甚至在目标时区.这是一个完全不同的时刻.(世界不会同步本地时钟.如果确实如此,我们就不需要时区!).
出于这个原因,即使上面的代码满足了问题,我强烈建议不要使用它.相反,重新评估您的要求,因为他们可能会误解时间和时区的性质.
时区不能仅由偏移完全表示.在时区标签wiki中阅读"Time Zone!= Offset" .虽然某些时区有固定的偏移量(例如印度使用的+05:30),但许多时区在一年中的不同时间点都会改变其偏移量,以适应夏令时.
如果您想对此进行说明,可以使用moment-timezone而不是调用utcOffset(...)
.但是,我的第一个项目中的问题仍然适用.
// get a moment representing the current time
var now = moment();
// create a new moment based on the original one
var another = now.clone();
// change the time zone of the new moment - passing true to keep the local time
another.tz('America/New_York', true); // or whatever time zone you desire
// log the output
console.log(now.format()); // "2016-01-15T11:58:07-08:00"
console.log(another.format()); // "2016-01-15T11:58:07-05:00"
Run Code Online (Sandbox Code Playgroud)
Joa*_*oao 10
投票最多的答案是凌乱的IMO.这是一个更清洁的解决方案 - 类似于BlueSam的答案,但更安全:
const myTime = moment.tz('2016-08-30T22:00:00', moment.ISO_8601, 'America/Denver')
myTime.format() //2016-08-30T22:00:00-06:00
const sameTimeDifferentZone = moment.tz(myTime.format('YYYY-MM-DDTHH:mm:ss.SSS'), moment.ISO_8601, 'America/New_York')
sameTimeDifferentZone.format() //2016-08-30T22:00:00-04:00
Run Code Online (Sandbox Code Playgroud)
小智 6
看完上面的评论后,我想我会根据Joao的回答加入.在我的情况下,我试图使用具有时区的预先存在的时刻日期并将其转换为另一个时区,同时保留原始日期值(如问题中所述).
var newTimezone = 'America/Denver';
//date - contains existing moment with timezone i.e 'America/New_York'
moment.tz(date.format('YYYY-MM-DDTHH:mm:ss'), 'YYYY-MM-DDTHH:mm:ss', newTimezone);
Run Code Online (Sandbox Code Playgroud)
从此刻文档: http: //momentjs.com/timezone/docs/
参考moment-timezone-with-data.js并指定要转到哪个时区,如下所示:
moment(date).tz("America/Los_Angeles").format()
Run Code Online (Sandbox Code Playgroud)