2017-07-04 43 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

相關問題