JavaScript RangeError: Invalid time value 错误
在无效日期调用方法时会出现“Uncaught RangeError: Invalid time value”错误,例如 new Date('asdf').toISOString()
。 要解决该错误,请在调用该方法之前有条件地检查日期是否有效。
console.log(new Date('asdf')); // 👉️ "Invalid Date"
// ⛔️ Uncaught RangeError: Invalid time value
const d = new Date('asdf').toISOString();
检查浏览器控制台或终端(如果使用 Node.js)中的错误消息。
上面的截图显示错误发生在 index.js 文件的第 4 行。
当提供的字符串不是有效日期时,Date()
构造函数返回“无效日期”值。 在无效日期调用方法会导致错误。
console.log(new Date('asdf')); // 👉️ Invalid Date
console.log(new Date('2022-32-33')); // 👉️ Invalid Date
console.log(new Date('one-two-20')); // 👉️ Invalid Date
要解决“Invalid time value”错误,请仅在有效日期对象上调用日期方法。
console.log(new Date(1317996123)); // 👉️ Fri Jan 16 ...
console.log(new Date('24 September 2022 15:30 UTC')); // 👉️ Sat Sep 24 ...
这是一个函数,我们可以使用它在调用方法之前验证日期。
function dateIsValid(date) {
return !Number.isNaN(new Date(date).getTime());
}
console.log(dateIsValid(1317996123)); // 👉️ true
console.log(dateIsValid('24 September 2022 15:30 UTC')); // 👉️ true
console.log(dateIsValid('asdf')); // 👉️ false
console.log(dateIsValid('2022-32-33')); // 👉️ false
如果日期无效,
getTime()
方法将返回一个 NaN(不是数字)值。
我们检查该值是否不是 NaN 并返回结果。 如果该值不是 NaN,则我们有一个可以安全调用方法的有效日期。
function dateIsValid(date) {
return !Number.isNaN(new Date(date).getTime());
}
const date = '2022-32-33';
if (dateIsValid(date)) {
console.log(new Date(date).toISOString());
} else {
// 👇️ this runs
console.log('not a valid date');
}
在对日期调用 toISOString()
方法之前,我们对其进行验证。 这使我们能够避免出现“Invalid time value” RangeError
。
总结
在无效日期调用方法时会出现“Uncaught RangeError: Invalid time value”错误,例如 new Date('asdf').toISOString()
。 要解决该错误,请在调用该方法之前有条件地检查日期是否有效。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。