簡體   English   中英

Moment TimeZone 以分鍾為單位返回不正確的 UTC 偏移量

[英]Moment TimeZone returns incorrect UTC Offset in minutes

我需要為將來的約會計算與 UTC 的分鍾偏移量。

約會的日期和時間由用戶在他們的本地日期和時間中輸入。

我需要 UTC 的偏移量,以便我的服務器可以在預約前一小時剩余 email。

我正在使用 Moment TimeZone 並且它返回正確的整體 TimeZone 但是當它以分鍾為單位計算 Offset 時它是錯誤的。

它返回我在提前一個小時的夏令時 - 但這是不正確的。

    var startDateTime = moment("2022-11-20 14:00");
    var startTimeStamp = startDateTime.format('X');
    
    // offset from UTC in minutes 
    var offsetMinutes = moment.tz.zone(moment.tz.guess(true)).utcOffset(startTimeStamp); 

    // abbreviated timezone name
    var timeZoneAbbr = moment.tz.zone(moment.tz.guess(true)).abbr(startTimeStamp);  


// Specific scenario is...
// TimeZone = Europe/London
// Date = 2022-11-20
// Time = 14:00

// Moment TimeZone returns...
// TimeZone = Europe/London - correct
// Offset in minutes = -60  - wrong it should be 0
// TimeZone abbreviation = BST (British Summer Time) - wrong - day light savings time ended last month

// NB: I am using this TimeZone library
// https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data-1970-2030.min.js

上面代碼的問題是.format('X')的使用,它將日期格式化為 unix 時間,即自 1970-01-01 以來的秒數。

時刻時區 function 期望這是一個毫秒值。 因此,您可以改用 .format('x') ,或者更簡單,只需將 moment 實例傳遞給函數,如下面的代碼所示。

 var timeZone = moment.tz.zone(moment.tz.guess(true)); var startDateTime = moment("2022-11-20 14:00"); console.log('Timezone:', timeZone.name); console.log('Offset (minutes):', timeZone.utcOffset(startDateTime)); console.log('Timezone abbr:', timeZone.abbr(startDateTime));
 .as-console-wrapper { max-height: 100%;important; }
 <script src="https://momentjs.com/downloads/moment.js"></script> <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM