我正在try 生成一个日期对象,然后将各种格式化的部分保存到变量中.所有它的工作,除了我似乎不能只生成/格式化时区名称本身.
下面的代码将产生3/20/2024, EDT
,但我只希望产生EDT
.
const timeZoneFormatter1 = new Intl.DateTimeFormat("en-US", {
timeZoneName: "short",
timeZone: "America/New_York",
});
console.log(timeZoneFormatter1.format(now));
我错过了什么 Select ?如何让它忽略日期信息而只生成时区名称?
我想我可以用'3/20/2024, EDT'.split(',')[1].trim()
手动得到它,但这对我来说感觉非常黑客.
这是我try 的一个工作演示
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());