我正在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());

推荐答案

您可以使用DateTimeFormat.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,
});

const parts = timeZoneFormatter1.formatToParts(now);
console.log('parts:', parts);

const tzName = parts.find(x => x.type === 'timeZoneName').value;
console.log('timeZoneName:', tzName);

Javascript相关问答推荐

当在select中 Select 选项时,我必须禁用不匹配的 Select

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

使用续集和下拉栏显示模型属性

在Vite React库中添加子模块路径

Chart.js 4.4.2,当悬停在一个数据点上时,如何在工具提示中拥有多个数据点/标签?

为什么按钮会随浮动属性一起移动?

简单的PayPal按钮集成导致404错误

编剧如何获得一个div内的所有链接,然后判断每个链接是否都会得到200?

Angular 中的类型错误上不存在获取属性

在执行异步导入之前判断模块是否已导入()

我创建了一个创建对象的函数,我希望从该函数创建的对象具有唯一的键.我怎么能做到这一点?

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

同一类的所有div';S的模式窗口

SPAN不会在点击时关闭模式,尽管它们可以发送日志(log)等

AJAX POST在控制器中返回空(ASP.NET MVC)

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

Node.js错误: node 不可单击或不是元素

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

由于http.get,*ngIf的延迟很大