分析上述两段示例,发现获取Date对象时,即使获取失败,也会得到一个Date对象,但这时已经不是正确的日期对象。
使用日期工具: date-fns
npm install date-fns --save # or with yarn yarn add date-fns let date_fns = require('date-fns') console.log(date_fns.isValid(new Date("abc"))) console.log(date_fns.isValid(new Date("2020-06-28 17:26:03"))) > false > true自定义方法
function isVaildDate(date) { return date instanceof Date && !isNaN(date.getTime()); } console.log(isVaildDate(new Date("abc"))) console.log(isVaildDate(new Date("2020-06-28 17:26:03"))) > false > true