date - 不同时区的同一日期

我的问题是如何在不同的时区获得相同的日、月、年、时、分、秒,例如:

var now = moment().valueOf();
var result1 = moment(now).format('DD-MM-YYYY HH:mm:SS Z');

在我的时区,我得到一些这样的:
18-02-2015 21:08:34 +01:00

那么如何只更改时区而不更改其他值(天,月,...,分钟,...)

我想得到这样的东西:
    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

提前致谢

最佳答案

以下是您可以按照您的要求执行的操作:

// 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"

但是,您必须认识到两件重要的事情:
  • another对象 不再代表当前时间 - 即使在目标时区。这是一个完全不同的时刻。 (世界不会同步本地时钟。如果同步了,我们就不需要时区了!)。

    因此,即使上面的代码满足了所提出的问题,我强烈建议不要使用它 .相反,请重新评估您的要求,因为他们可能误解了时间和时区的性质。
  • 时区不能仅由偏移量完全表示。阅读 the timezone tag wiki 中的“时区!= 偏移量” .虽然一些时区有固定的偏移量(例如印度使用的 +05:30),但许多时区在一年中的不同时间点改变它们的偏移量以适应 daylight saving time .
  • 如果你想解决这个问题,你可以使用 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"
    

    https://stackoverflow.com/questions/28593304/

    相关文章:

    actionscript-3 - AS3在第一个音频文件完成播放后播放第二个音频文件

    visual-studio-2008 - midl : error MIDL9008

    python - Mac OS X中的python错误 undefined symbol : “_P

    .net - Visual Studio Web引用错误

    spring - 哪个工具可以验证 Spring 配置

    compiler-errors - mingw提供错误-C编译器无法创建可执行文件

    python - 安装Python库时出错?

    emacs - 字节编译错误

    ruby - 无法安装rmagick

    installation - 编译后ISTool错误