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 的月份。
添加回答
舉報