如何全局设置网站的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
相关产品推荐
相关产品推荐

