亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript 中的時區敏感日期比較

Javascript 中的時區敏感日期比較

慕無忌1623718 2023-06-15 17:11:04
我正在確定 Ember 應用程序中 Javascript 中兩個日歷日期之間的差異。我目前正在使用 date-fns 的 differenceInCalendarDays。現在主要提供了所需的結果,唯一的問題是我需要處理計算對時區(不是瀏覽器的本地時區)敏感的 2 個日期之間的差異。據我所知,JS 日期被跟蹤為 UTC,日期對象本身沒有存儲時區。我在 JS 中完成的任何時區本地化都輸出了一個字符串。在考慮時區的同時,是否有一個好的庫或方法來完成 differenceInCalendarDays?const daysAgo = this.intl.formatRelative(-differenceInCalendarDays(new Date(), someOtherDay), {    unit: 'day',     numeric: 'auto',     timeZone: 'this.intl.timeZone});這是我正在做的事情的一個小樣本,顯然 differenceInCalendarDays 將解析為一個不考慮任何時區的數字。differenceInDays 的文檔對瀏覽器的本地時間時區敏感(這在這里沒有幫助),但 differenceInCalendarDays 沒有這樣的提及。任何幫助將不勝感激!
查看完整描述

1 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

從邏輯上講,兩個日歷日期之間的差異(例如2020-01-01和 )2020-01-02對時區不敏感,也根本不涉及時間。正好是一天。在這種情況下,一天不是 24 小時,而是一年的邏輯劃分。把它想象成紙質日歷上的一個正方形。


但是 - 在任何給定時刻,兩個不同的時區可能在同一日歷日期,或者它們可能在兩個不同的日歷日期。因此,在確定“現在”(或“今天”、“昨天”、“明天”等)日期時,時區很重要


為了說明這兩點并希望回答您的問題,可以使用以下代碼獲取給定時區自“今天”以來經過的天數:


function daysSince(year, month, day, timeZone) {


  // Create a DateTimeFormat object for the given time zone.

  // Force 'en' for English to prevent issues with languages that don't use Arabic numerals.

  const formatter = new Intl.DateTimeFormat('en', { timeZone });

  

  // Format "now" to a parts array, then pull out each part.

  const todayParts = formatter.formatToParts();  // now is the default when no Date object is passed.

  const todayYear = todayParts.find(x=> x.type === 'year').value;

  const todayMonth = todayParts.find(x=> x.type === 'month').value;

  const todayDay = todayParts.find(x=> x.type === 'day').value;

  

  // Make a pseudo-timestamp from those parts, abusing Date.UTC.

  // Note we are intentionally lying - this is not actually UTC or a Unix/Epoch timestamp.

  const todayTimestamp = Date.UTC(+todayYear, todayMonth-1, +todayDay);


  // Make another timestamp from the function input values using the same approach.

  const otherTimestamp = Date.UTC(+year, month-1, +day);


  // Since the context is the same, we can subtract and divide to get number of days.

  return (todayTimestamp - otherTimestamp) / 864e5;

}


// example usage:

console.log("US Pacific: " + daysSince(2020, 1, 1, 'America/Los_Angeles'));

console.log("Japan: " + daysSince(2020, 1, 1, 'Asia/Tokyo'));


此方法僅適用于 UTC 沒有轉換(例如 DST 或標準時間偏移的更改)。


另請注意,我在這里不使用Date對象,因為我們必須非常小心這些對象的構造方式。如果您只有一個Date來自日期選擇器 UI 的對象,則該對象很可能是在假設本地時間的情況下創建的——而不是特定時區的時間。因此,在繼續之前,您需要從該對象中取出年、月和日。例如:


daysSince(dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), 'America/New_York');

密切注意 +1 和 -1。該Date對象使用基于 0 的月份,但我更喜歡基于 1 的月份。


查看完整回答
反對 回復 2023-06-15
  • 1 回答
  • 0 關注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號