转换时的奇数时区偏移

Odd timezone offset when converting

我正在尝试尽可能使用 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,正如预期的那样,因为 'Europe/Berlin' 比 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 谁能提示我为什么我的期望是错误的?

(希望我的英文没问题。)

我认为我们不能直接回答这个问题,因为看起来问题是 Utilities.formatDate 使用 12:00 表示午夜(是在许多系统中书写午夜的两种有效方式之一,尤其是在使用 12 小时制时,尽管通常您会在它后面加上一些表示它是 12:00 a.m,而不是 12:00 p.m.)。例如,这是另一个格式化程序的示例,因为我明确告诉它使用 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 的偏移量,有时是两个小时的偏移量(夏令时)。¹相反,我有一个格式化程序在 DategetUTCHoursgetUTCMonth 等上使用 UTC 访问器。 ) 构建字符串而不是使用本地时间版本。要么是某个库,要么是使用 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)}`);


¹ 请记住,UTC 是不变的,它没有夏令时。