2017-07-04 44 views
1

他的测试代码:使用momentjs,得到当地不同的结果VS Azure上

var c = moment().tz('America/New_York'); 
console.log('c.format: ' + c.format()); 

var b = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]).tz('America/Chicago'); 
console.log("b.format: " + b.format()); 

当我在本地运行这段代码,我得到:

c.format: 2017-07-03T16:33:42-04:00 
b.format: 2017-07-03T16:33:00-05:00 

这是我期望(和希望)即将发生。基本上我只想抽出一点时间,在不改变实际时间的情况下改变偏移量。然而,当我运行通过我的Azure中托管的应用程序,同样的代码,输出是这样的:

c.format: 2017-07-03T16:43:16-04:00 
b.format: 2017-07-03T11:43:00-05:00 

本地和Azure的应用程序都运行同一版本的节点(8.0.0),以及时刻(2.18 .1)和瞬时时区(0.5.13)。

任何人有任何想法可能会导致此?谢谢!

回答

1

正如docs说:

默认情况下,时刻解析并在本地时间显示。

为了您b变量正在创建使用c.year(), c.month(), c.date(), c.hours(), c.minutes()当地某个时刻的对象,所以转换bAmerica/Chicago时区将取决于系统的结果。

您可以使用moment.tz创建了一会儿对象,指定时区(例如,America/New_York),你的情况,是这样的:

moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York') 

这里的一个片段显示在不同的情况下,实时的结果:

// Current time in New York 
 
var c = moment().tz('America/New_York'); 
 
console.log('c.format: ' + c.format()); 
 

 
// Create a local moment object for the current time in New York 
 
var mLocal = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]); 
 
console.log("mLocal.format: " + mLocal.format()); 
 

 
// Convert local moment to America/Chicago timezone 
 
var b = mLocal.tz('America/Chicago'); 
 
console.log("b.format: " + b.format()); 
 

 
// Create moment object for the current time in New York 
 
// specifying timezone and then converting to America/Chicago timezone 
 
var b1 = moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York').tz('America/Chicago'); 
 
console.log("b1.format: " + b1.format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>

+1

谢谢!现在我觉得自己像个白痴。我在其他地方使用了moment.tz语法,我甚至没有意识到它们之间的差异。我尝试在计算机上本地更改我的时区,但仍然得到了正确的结果,所以我认为这不是因为服务器和我处于不同的时区。猜测时刻对于手动更改时区太聪明!欣赏它。 – Keirathi

相关问题