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

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

示例

1
2
3
4
5
6
7
8
var date = new Date("abc");
console.log(date.toString());
console.log(typeof date);
console.log(date instanceof Date);

> "Invalid Date"
> "object"
> true

1
2
3
4
5
6
7
8
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

    1
    2
    3
    npm install date-fns --save
    # or with yarn
    yarn add date-fns

    1
    2
    3
    4
    5
    6
    7
    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
  • 自定义方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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