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

date.GetMonth()不是函数

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

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

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

谢谢

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


函数是getMonth(),而不是getMonth(。

无论如何,您可以通过执行此操作来检查对象是否具有getMonth属性。这并不一定意味着对象是Date,而是任何具有getMonth属性的对象。

if (date.getMonth) {
    var month = date.getMonth();
}

您可以检查是否存在特定于Date对象的函数:

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

如上所述,在使用函数之前只检查函数是否存在可能是最简单的。如果您真的关心它是Date,而不仅仅是带有getMonth()函数的对象,请尝试以下操作:

function isValidDate(value) {
    var dateWrapper = new Date(value);
    return !isNaN(dateWrapper.getDate());
}

这将创建值的克隆(如果它是日期),或创建无效日期。然后可以检查新日期的值是否无效。


作为通过

typeof date.getMonth === 'function'

您可以使用instanceof运算符,即,对于无效日期,它也将返回true,例如,new Date('random_string')也是Date的实例

date instanceof Date

如果对象跨越帧边界传递,则此操作将失败。

解决方法是通过

Object.prototype.toString.call(date) === '[object Date]'

实际日期的类型为Object。但是您可以检查对象是否具有getMonth方法,以及它是否可调用。

function getFormatedDate(date) {
    if (date && date.getMonth && date.getMonth.call) {
       var month = date.getMonth();
    }
}

对于所有类型,我都编写了一个Object原型函数。这可能对你有用

Object.prototype.typof = function(chkType){
      var inp        = String(this.constructor),
          customObj  = (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9),
          regularObj = Object.prototype.toString.apply(this),
          thisType   = regularObj.toLowerCase()
                        .match(new RegExp(customObj.toLowerCase()))
                       ? regularObj : '[object '+customObj+']';
     return chkType
            ? thisType.toLowerCase().match(chkType.toLowerCase()) 
               ? true : false
            : thisType;
}

现在,您可以像这样检查任何类型:

var myDate     = new Date().toString(),
    myRealDate = new Date();
if (myRealDate.typof('Date')) { /* do things */ }
alert( myDate.typof() ); //=> String

[编辑2013年3月]基于不断进步的洞察力,这是一种更好的方法:

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im)
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
   ,Other = function(){ /* ... */}
   ,some = new Some;
2..is(String,Function,RegExp);        //=> false
2..is(String,Function,Number,RegExp); //=> true
'hello'.is(String);                   //=> true
'hello'.is();                         //-> String
/[a-z]/i.is();                        //-> RegExp
some.is();                            //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other);                       //=> false
some.is(Some);                        //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number);                 //=> true

您可以使用以下代码:

(myvar instanceof Date) // returns true or false

如果该函数为Date,则返回true,否则返回false:

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
} 

UndercoreJS和Lodash有一个名为.isDate()的函数,这似乎正是您所需要的。值得一看它们各自的实现:Lodash isDate、UndercoreJs


也可以使用简短形式

function getClass(obj) {
  return {}.toString.call(obj).slice(8, -1);
}
alert( getClass(new Date) ); //Date

或者类似的东西:

(toString.call(date)) == 'Date'

我找到的最佳方法是:

!isNaN(Date.parse("some date test"))
//
!isNaN(Date.parse("22/05/2001"))  // true
!isNaN(Date.parse("blabla"))  // false

你就不能用

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

为了检查该值是否是标准JS日期对象的有效类型,可以使用此谓词:

function isValidDate(date) {
  return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}

date检查参数是否不是错误值(undefined、null、0、“”等)Object.prototype.toString.call(date)返回给定对象类型的本机字符串表示形式-在我们的例子中是“[Object date]”。因为date.toString()重写了它的父方法,所以我们需要直接调用或应用Object.prototype中的方法。。绕过具有相同构造函数名称的用户定义对象类型(例如:“Date”)与instanceof或Date.prototype.isPrototypeOf不同,可以跨不同的JS上下文(例如iframes)工作。!isNaN(date)最后检查该值是否不是无效日期。


我一直在使用一种更简单的方法,但不确定这是否仅在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无效,因为它们没有构造函数。


还有一种变体:

Date.prototype.isPrototypeOf(myDateObject)

使用try/catch的方法

函数getFormattedDate(date=new date()){尝试{date.toISOString();}捕获(e){date=新日期();}返回日期;}console.log(getFormattedDate());console.log(getFormattedDate('AAAA'));console.log(getFormattedDate(新日期('AAAA')));console.log(getFormattedDate(新日期(2018,2,10));


您可以使用以下方法代替所有的变通方法:

dateVariable = new Date(date);
if (dateVariable == 'Invalid Date') console.log('Invalid Date!');

我发现这个黑客更好!


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

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


受这个答案的启发,这个解决方案在我的情况下有效(我需要检查从API收到的值是否为日期):

!isNaN(Date.parse(new Date(YourVariable)))

通过这种方式,如果它是来自客户端或任何其他对象的随机字符串,您可以发现它是否是类似日期的对象。


如果您不关心iframes/其他上下文,这是一种非常简单的方法。

// isNaN(Invalid Date) == true
if (date instanceof Date && !isNaN(date)) { // isNaN wont accept a date in typescript, use date.getTime() instead to produce a number
    console.log("is date!");
}

检查对象是否实际上是日期,而不是看起来像日期的对象。任何对象都可以有getMonth函数。确保日期不是无效日期不将值传递到新的Date()中,其中数字甚至字符串都可以转换为Date。

如果您需要支持iframes和不同的上下文,您可以使用接受的答案,但添加额外的检查以识别无效日期。

// isNaN(Invalid Date) == true
if (Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date)) {
    console.log("is date!");
}


如果您使用的是Typescript,可以使用Date类型进行检查:

const formatDate( date: Date ) => {}

使用以下方法,您甚至可以将日期no检查为“无效日期”

if(!!date.getDate()){
    console.log('date is valid')
}

我在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);
}

只需使用瞬间

import moment from 'moment';

moment(myvar).isValid(); //  return true or false

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

常量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(“无效内容”))