JavaScript 日期格式化报错解析与解决

问题背景
在 JavaScript 开发过程中,日期格式化是一个常见的操作,在实际开发中,我们可能会遇到各种日期格式化报错,本文将针对这些报错进行解析,并提供相应的解决方法。
常见日期格式化报错
Invalid Date报错
当使用 new Date() 构造函数创建日期对象时,如果传入的参数不符合日期格式,将会抛出 Invalid Date 报错。
let date = new Date("2022/13/01"); 解决方法:
确保传入的日期字符串符合 ISO 8601 格式,
let date = new Date("2022-13-01"); RangeError报错
在设置日期对象的年、月、日、时、分、秒等属性时,如果值超出范围,将会抛出 RangeError 报错。
let date = new Date(); date.setFullYear(10000); // 抛出 RangeError
解决方法:

确保设置的日期值在有效范围内,年份应在 1900 到 9999 之间。
TypeError报错
在日期格式化函数中,如果传入的参数类型不正确,将会抛出 TypeError 报错。
let date = new Date();
console.log(date.format("yyyy-MM-dd")); // 抛出 TypeError 解决方法:
确保传入的参数类型正确,格式化函数可能需要传入一个字符串类型的格式参数。
日期格式化函数
Date.prototype.toISOString()
将日期对象转换为 ISO 8601 格式的字符串。
let date = new Date(); console.log(date.toISOString()); // "2022-12-01T00:00:00.000Z"
Date.prototype.toLocaleString()
将日期对象转换为本地格式的字符串。
let date = new Date(); console.log(date.toLocaleString()); // "2022/12/01 下午12:00:00"
Date.prototype.format()
自定义日期格式化函数。

Date.prototype.format = function (format) {
let o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours(), // 小时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds(), // 毫秒
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(o[k].length));
}
}
return format;
};
let date = new Date();
console.log(date.format("yyyy-MM-dd")); // "2022-12-01" FAQs
Q1:如何避免 Invalid Date 报错?
A1:确保传入的日期字符串符合 ISO 8601 格式,"2022-12-01"。
Q2:如何解决 RangeError 报错?
A2:确保设置的日期值在有效范围内,例如年份应在 1900 到 9999 之间。

