Intl.DateTimeFormat的bug

返回
Author Avatar
钢翼
2020-05-20
编程
91

关于js内置国际化函数Intl.DateTimeFormat的bug。

最近用fullcalendar4时,发现底层格式化日期用的Intl.DateTimeFormat函数。这个函数在处理0:00到0:59的时间格式化会让人迷惑。

以下代码在各个浏览器控制台输出情况:

chrome

console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: true,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出"上午12:30"
console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: false,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出"24:30"

火狐

console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: true,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出""上午12:30"
console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: false,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出"00:30"

ie 11

console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: true,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出"‎上午‎ ‎12‎:‎30"
console.log(new Intl.DateTimeFormat('zh-cn',{hour: "numeric",hour12: false,minute: "2-digit"}).format(new Date('2015-05-01T00:30')))
//输出"‎0‎:‎30"


很明显,12小时制显示都出现了问题。24小时制,chrome会出现超过24小时的显示时间,这是不符合人类基本认知的,至少中国人不会觉得这个时间显示是正常的。


fullcalendar官方给出了两个解决方案,一个是将语言改成en-GB,要不引入momentjs格式化工具。


问题总归是可以解决的,但我觉得最好的方式应该是浏览器将这个内置函数的bug修复,凭啥只有语言是英国英语en-GB才能正常格式化。