平时开发的时候对日期和时间进行运算和格式化,可能经常使用 new Date(),但是它的用法和一些怪异设定并不是很方便好用,一不小心就踩坑。
new Date() 的四宗罪
浏览器不兼容
new Date('2023-1-1')
上面这行代码在 Safari 浏览器,返回的都是 Invalid Date。Safari 浏览器目前还理解不了 YYYY-MM-DD 这样的格式,只支持 YYYY/MM/DD。这就造成在 Windows 环境下的代码正常原型,而 Macbook 和 iPhone 用户异常显示;
月份的索引起点
new Date(2023, 1, 1) // 2023年2月1日
月份的索引是以 0 为起点的,而年份、日期却不是,同样的,对应的方法 setMonth() 也是从 0 开始设置的;
年份初始化不统一
当需要格式化公元元年至公元 100 年之间的时间,需要特殊的写法:
new Date(2023, 1, 1) // Wed Feb 01 2023 00:00:00 GMT+0800 (中国标准时间)
new Date(50, 2, 1) // Wed Mar 01 1950 00:00:00 GMT+0800 (中国标准时间)
new Date('0050-02-01') // Tue Feb 01 0050 08:05:43 GMT+0805 (中国标准时间) √
new Date() 第一个参数年份小于 100 的话,会自动加上 1900 年,所以需要用 YYYY-MM-DD 格式的时间字符串作为第一个参数...但是如果给公元 100 年前添加上时间,又有不一样的表现:
new Date('0050-02-01 00:00:00') // Wed Feb 01 1950 00:00:00 GMT+0800 (中国标准时间)
当以 YY-MM-DD 这种字符串格式作为参数的时候,构造函数把最后面那个当作年份,而且默认它为 20xx 年
new Date('10-11-12') // Thu Oct 11 2012 00:00:00 GMT+0800 (中国标准时间)