2017-08-08 486 views
1

我有一個UTC日期時間字符串和時區名稱。我從第三方API獲取此信息。我需要使用JavaScript/NodeJS將UTC時間轉換爲該時區的本地時間,並獲取該時區的當前時間。有沒有相同的圖書館/方法?JavaScript:使用時區將UTC時間轉換爲本地時間

var timezone = "America/New_York";//This will always be in Olson format. 
var UTCTime = "2017-09-03T02:00:00Z"; 
var localTime; //I need to find the equivalent of UTCTime for America/New_York 
var currentTime; //Current time of time zone America/New_York 
+0

有用的資源https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date – Atiq

+0

時刻(http://momentjs.com/docs/)是一個非常強大和流行的日期操作庫,很可能你的需求可以被它覆蓋。 – tibetty

回答

0

這可以通過幾種方式來完成:

var options = { 
    timeZone: "America/New_York", 
    year: 'numeric', month: 'numeric', day: 'numeric', 
    hour: 'numeric', minute: 'numeric', second: 'numeric' 
}; 

var formatter = new Intl.DateTimeFormat([], options); 

var UTCTime = "2017-09-03T02:00:00Z"; 
var localTime = formatter.format(new Date(UTCTime)); 
var currentTime = formatter.format(new Date()); console.log(currentTime, localTime); 

或者您可以使用moment.js庫。

0

您可以使用getTimezoneOffset(),以分鐘爲單位返回偏移量。然後你可以修改你的日期到相應的函數返回。

你可能也想看看moment.js這是一個非常有用的圖書館,當談到javascipt日期。

相關問題