如何使用 date-fns 更正时区?

How to correct the time-zone with date-fns?

(在线查看此示例:https://stackblitz.com/edit/date-fns-playground-zeitzonen?file=index.ts -> 控制台输出)

如下情况,是11:54上午:

// Setup
const dateString = "2020-08-30T11:54:48.200Z";    // <---- 11:54 AM
const tz = "Europe/Berlin";
const dateFormat = "d. MMM yyyy, E HH:mm";
const dateOptions = { locale: de }; 

就我格式化日期而言,它更改了时区并增加了 2 个小时:

const parsedDate = parseISO(dateString);

const formattedDate = format(parsedDate, dateFormat, dateOptions);
// outputs: 30. Aug 2020, So. 13:54

const zonedDate = utcToZonedTime(dateString, tz);
// outputs: 2020-08-30T11:54:48.200Z

const formattedZonedDate =  format(zonedDate, dateFormat, dateOptions);
// outputs: 30. Aug 2020, So. 13:54

期望的(正确的)输出是 30. Aug 2020, So. 11:54

我的错误在哪里?首字母 dateString 的时区是否正确?

Does the initial dateString have the correct time zone?

如果您希望它在柏林时间,则不会。末尾的“Z”表示“UTC”-因此您的字符串表示 11:54 UTC,在柏林确实是 13:54。在我看来,格式正确。

诚然,我不完全清楚为什么 utcToZonedDateTime 仍然报告 UTC 值而不是分区版本。

如果要dateString代表当地时间,大概应该是“2020-08-30T11:54:48.200”。另一方面,如果您希望它代表 在柏林 11:54 的 UTC 时间,则它应该是“2020-08-30T09:54:48.200Z " - 请注意将小时更改为 09。