You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何全局设置网站的Intl.DateTimeFormat hourCycle参数

全局设置Intl.DateTimeFormat的hourCycle

可以通过重写原生Intl.DateTimeFormat构造函数来全局指定hourCycle参数,统一所有基于Intl的日期格式化行为(包括SyncFusion EJ2这类第三方库的调用)。

具体实现代码

// 保存原生构造函数引用
const OriginalDateTimeFormat = Intl.DateTimeFormat;

// 重写构造函数,默认注入hourCycle配置
Intl.DateTimeFormat = function(locales, options = {}) {
  // 未显式指定hourCycle时,强制使用h23(0-23小时制)
  if (!options.hourCycle) {
    options.hourCycle = 'h23';
  }
  return new OriginalDateTimeFormat(locales, options);
};

// 同步原生构造函数的静态属性,保证兼容性
Intl.DateTimeFormat.supportedLocalesOf = OriginalDateTimeFormat.supportedLocalesOf;
Intl.DateTimeFormat.prototype = OriginalDateTimeFormat.prototype;

关键说明

  • 这段代码会拦截所有new Intl.DateTimeFormat()的调用,当没有手动传入hourCycle参数时,自动添加hourCycle: 'h23'配置,强制统一为0-23小时格式,解决Chrome和Firefox的显示差异。
  • 第三方库如SyncFusion EJ2内部若依赖原生Intl进行日期格式化,会自动遵循这个全局设置,无需修改库的源码或逐个调整调用位置。
  • 若特定场景需要使用其他小时制,只需显式传入hourCycle参数即可覆盖全局配置,比如new Intl.DateTimeFormat('en-US', { hourCycle: 'h12' })。

内容的提问来源于stack exchange,提问作者Andrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:15:37