我正在嘗試盡可能使用 UTC。現在我發現了以下奇怪的行為,我真的不明白發生了什么。如果有人可以提供建議,那就太好了。
注意:我在 Google Apps 腳本編輯器中撰寫代碼。
我使用以下代碼創建日期并在本地時區獲取輸出:
var testDate = Date.UTC(2022,0,1,0,0,0,0);
Logger.log(Utilities.formatDate(new Date(testDate), 'Europe/Berlin', 'dd.MM.yyyy hh:mm'));
結果01.01.2022 01:00正如預期的那樣,因為“歐洲/柏林”比 UTC 晚 1 小時。因此,如果我想要輸出,01.01.2022 00:00我會嘗試以下操作:
var testDate = Date.UTC(2021,11,31,23,0,0,0);
Logger.log(Utilities.formatDate(new Date(testDate), 'Europe/Berlin', 'dd.MM.yyyy hh:mm'));
但我得到的結果是:01.01.2022 12:00
有人能暗示我為什么我的期望是錯誤的嗎?
(我希望我的英語沒問題。)
uj5u.com熱心網友回復:
我不認為我們可以直接回答這個問題,因為看起來問題是Utilities.formatDate使用 12:00 表示午夜(這是許多系統中撰寫午夜的兩種有效方式之一,尤其是在使用 12 小時制時,盡管通常您會在后面加上一些指示它是上午 12:00,而不是下午 12:00 的內容)。例如,這是另一個格式化程式的示例,因為我明確告訴它使用 12 小時時間:
顯示代碼片段
const testDate = Date.UTC(2022,0,1,0,0,0,0);
const dateTimeFormat = new Intl.DateTimeFormat("en", {
hour12: true,
timeZone: "UTC",
timeStyle: "short",
}).format;
console.log(dateTimeFormat(testDate));
因此,您必須Utilities.formatDate查看它是否可以選擇 24 小時制或至少00:00用于午夜,就像其他一些格式化程式一樣。
但更根本的是,如果您嘗試以 UTC 格式進行格式化,我不會玩偏移游戲來執行此操作,尤其是因為柏林并不總是與 UTC 偏移一小時,有時會偏移兩個小時(夏令時)。 1相反,我有一個使用UTC訪問器上格式化Date(getUTCHours,getUTCMonth,等)來構建字串,而不是使用本地時間版本。要么是某個庫,要么是使用Intl.DateTimeFormat. 例如:
顯示代碼片段
const testDate = Date.UTC(2022,0,1,0,0,0,0);
const dateTimeFormat = new Intl.DateTimeFormat("de", {
timeZone: "UTC",
dateStyle: "medium",
timeStyle: "short",
}).format;
// Outputs "01.01.2022, 00:00", which is close to but
// not quite the same as your desired format
console.log(dateTimeFormat(testDate));
// Outputs your desired format, but may not be flexible across locales
const dateFormat = new Intl.DateTimeFormat("de", {
timeZone: "UTC",
dateStyle: "medium",
}).format;
const timeFormat = new Intl.DateTimeFormat("de", {
timeZone: "UTC",
timeStyle: "short",
}).format;
console.log(`${dateFormat(testDate)} ${timeFormat(testDate)}`);
1 請記住,UTC 是不變的,它沒有夏令時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/404511.html
標籤:
