为什么在设置(无效)日期时JavaScript为什么返回“无效日期”?似乎它应该出错/抛出异常并使其难以处理任何错误。
问题:处理此问题的最佳方法是在“更新日期”后检查日期值,以查看该值是否实际上是日期或“无效日期”的字符串值?
const validDate = new Date();
console.log('validDate instanceof Date:', validDate instanceof Date);
const invalidDate = new Date('asdfasdfasdf');
console.log('invalidDate instanceof Date:', invalidDate instanceof Date);
if (invalidDate) {
// This hits because invalidDate is now a string and is therefore truthy
console.log('Date is Valid');
}
if (invalidDate instanceof Date) {
// This hits because it's still an instance of date (although the value is a string)
console.log('Date is Valid');
}
if (typeof invalidDate === 'string') {
// Doesnt hit because invalidDate is not a string
}
答案 0 :(得分:0)
尝试以下代码:
const invalidDate = new Date('aksjdhaksjdh');
console.log('invalidDate instanceof Date:', invalidDate.setUTCHours(0) instanceof Date);
setUTCHours()方法根据UTC时间设置日期对象的小时。在这种情况下,由于我们的var无效,因此无法将其转换并返回false。