我正在尝试生成一个日期对象,然后将各种格式化部分保存到变量中。除了我似乎无法自己生成/格式化时区名称之外,所有这些都有效。
以下代码将生成
3/20/2024, EDT
但我只想生成 EDT
。
const timeZoneFormatter1 = new Intl.DateTimeFormat("en-US", {
timeZoneName: "short",
timeZone: "America/New_York",
});
console.log(timeZoneFormatter1.format(now));
我缺少哪些选项?如何让它省略日期信息并仅生成时区名称?
我想我可以用
'3/20/2024, EDT'.split(',')[1].trim()
手动获取它,但这对我来说感觉很老套。
这是我尝试的工作演示
const now = new Date();
const locale = "en-US";
const timeZone = "America/New_York"; //always use HQ local time zone
const dateFormatter = new Intl.DateTimeFormat(locale, {
weekday: "short",
month: "short",
day: "numeric",
timeZone,
});
console.log('Date:', dateFormatter.format(now));
const timeFormatter = new Intl.DateTimeFormat(locale, {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone,
});
console.log('Time:', timeFormatter.format(now));
const timeZoneFormatter1 = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #1:', timeZoneFormatter1.format(now));
const timeZoneFormatter2 = new Intl.DateTimeFormat(locale, {
month: undefined,
day: undefined,
year: undefined,
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #2:', timeZoneFormatter2.format(now));
const timeZoneFormatter3 = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #3 (hacky):', timeZoneFormatter2.format(now).split(',')[1].trim());
Intl.DateTimeFormat 构造函数不直接支持仅格式化时区名称而不包含其他日期或时间组件。
但是,您可以通过格式化仅包含时区信息的固定日期,然后从中提取时区名称来实现此目的。
const now = new Date();
const locale = "en-US";
const timeZone = "America/New_York"; // Always use HQ local time zone
// Format a fixed date (Unix epoch) to get only the time zone name
const timeZoneFormatter = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false, // Use 24-hour format to avoid ambiguity
timeZone,
});
// Format a fixed date (Unix epoch) to get only the time zone name
const timeZoneName = timeZoneFormatter.format(0).split(' ')[1]; // Extracting the time zone name
console.log('Time Zone:', timeZoneName);
您可以使用
formatToParts()
并使用 timeZoneName
部分的值。
const now = new Date();
const locale = "en-US";
const timeZone = "America/New_York"; //always use HQ local time zone
const dateFormatter = new Intl.DateTimeFormat(locale, {
weekday: "short",
month: "short",
day: "numeric",
timeZone,
});
console.log('Date:', dateFormatter.format(now));
const timeFormatter = new Intl.DateTimeFormat(locale, {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone,
});
console.log('Time:', timeFormatter.format(now));
const timeZoneFormatter1 = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
timeZone,
});
console.log('timeZoneName:', timeZoneFormatter1.formatToParts(now).find(x => x.type === 'timeZoneName').value);