JS 如何判断字符串转换的Date对象是否有效, Invalid Date{}

    技术2022-07-11  75

    JS 如何判断字符串转换的Date对象是否有效, Invalid Date{}

    示例

    var date = new Date("abc"); console.log(date.toString()); console.log(typeof date); console.log(date instanceof Date); > "Invalid Date" > "object" > true var date = new Date("2020-06-28 17:26:03"); console.log(date.toString()); console.log(typeof date); console.log(date instanceof Date); > "Sun Jun 28 2020 17:26:03 GMT+0800 (China Standard Time)" > "object" > true

    分析上述两段示例,发现获取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
    Processed: 0.012, SQL: 9