我在网页上有一个烦人的bug:

date.GetMonth()不是函数

所以,我想我做错了什么。变量date不是date类型的对象。如何在Javascript中检查数据类型?我试图添加一个if(日期),但不起作用。

function getFormatedDate(date) {
    if (date) {
       var month = date.GetMonth();
    }
}

所以,如果我想编写防御性代码并防止日期(不是一个)被格式化,我该怎么做?

谢谢

UPDATE:我不想检查日期的格式,但我想确保传递给getFormatedDate()方法的参数是date类型。


当前回答

我在React钩子上遇到了一些问题,其中Date将在稍后出现/延迟加载,然后初始状态不能为null,它不会通过ts检查,但显然空Object会成功!:)

const [birthDate, setBirthDate] = React.useState({})

<input
  value={birthDate instanceof Date ? birthDate.toISOString() : ''}
  name="birthDay"
/>

其他回答

我在React钩子上遇到了一些问题,其中Date将在稍后出现/延迟加载,然后初始状态不能为null,它不会通过ts检查,但显然空Object会成功!:)

const [birthDate, setBirthDate] = React.useState({})

<input
  value={birthDate instanceof Date ? birthDate.toISOString() : ''}
  name="birthDay"
/>

箭头函数

const isValidDate = (value: any) => value instanceof Date && !isNaN(value);

功能:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

检测有效日期的最简单方法。

常量isDate=(str)=>{let timestamp=Date.parse(str);if(!isNaN(timestamp))返回新日期(timestaff);return false}console.log(isDate(“2020-11-11T12:55.123Z”))console.log(isDate(“17/7/22024”))console.log(“getMonth:”,isDate(“17/July/2024”).getMonth())console.log(isDate(“无效内容”))

我们也可以通过以下代码验证它

var a = new Date();
a.constructor === Date
/*
true
*/

我一直在使用一种更简单的方法,但不确定这是否仅在ES6中可用。

let a = {name: "a", age: 1, date: new Date("1/2/2017"), arr: [], obj: {} };
console.log(a.name.constructor.name); // "String"
console.log(a.age.constructor.name);  // "Number"
console.log(a.date.constructor.name); // "Date"
console.log(a.arr.constructor.name);  // "Array"
console.log(a.obj.constructor.name);  // "Object"

然而,这对null或undefined无效,因为它们没有构造函数。