如何检查对象是否为日期?

时间:2022-05-26 07:23:28

I have an annoying bug in on a webpage: "date.GetMonth() is not a function". So I suppose that I am doing something wrong since somewhere and the object date is not an object of type Date. How can I check for a datatype in Javascript? I tried to add a if(date) but it doesn't work.

我在网页上有一个烦人的错误:“date.GetMonth()不是函数”。所以我认为我做错了什么,因为对象日期不是类型为date的对象。如何在Javascript中检查数据类型?我试图添加一个if(date),但它不起作用。

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

So if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?

因此,如果我想编写防御代码并阻止日期(不是日期)被格式化,我该怎么做呢?

Thanks!

谢谢!

UPDATE: I don't want to check the format of the date, but I want to be sure that the parameter passed to the method getFormatedDate is of type Date.

更新:我不想检查日期的格式,但是我想确定传递给方法getFormatedDate的参数是类型日期。

15 个解决方案

#1


777  

As an alternative to duck typing via

作为一种替代方法,通过

typeof date.getMonth === 'function'

you can use the instanceof operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string') is also instance of Date

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

date instanceof Date

This will fail if objects are passed across frame boundaries.

如果跨框架边界传递对象,则会失败。

A work-around for this is to check the object's class via

解决这个问题的方法是通过检查对象的类

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

#2


85  

You can use the following code:

您可以使用以下代码:

(myvar instanceof Date) // returns true or false

#3


36  

The function is getMonth(), not GetMonth().

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

Anyway, you can check if the object has a getMonth property by doing this. It doesn't necessarily mean the object is a Date, just any object which has a getMonth property.

无论如何,通过这样做,您可以检查对象是否具有getMonth属性。它并不一定意味着对象是日期,只是任何具有getMonth属性的对象。

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

#4


15  

For all types I cooked up an Object prototype function. It may be of use to you

对于所有类型,我都设计了一个对象原型函数。这可能对你有用

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;
}

Now you can check any type like this:

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

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

[Edit march 2013] based on progressing insight this is a better method:

[编辑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

#5


15  

As indicated above, it's probably easiest to just check if the function exists before using it. If you really care that it's a Date, and not just an object with a getMonth() function, try this:

如上所述,在使用函数之前,最好检查函数是否存在。如果您真的关心它是一个日期,而不是一个具有getMonth()函数的对象,请尝试以下方法:

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

This will create either a clone of the value if it's a Date, or create an invalid date. You can then check if the new date's value is invalid or not.

如果值是日期,则创建该值的克隆,或者创建无效的日期。然后可以检查新日期的值是否无效。

#6


8  

In order to check if the value is a valid type of the standard JS-date object, you can make use of this predicate:

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

function isValidDate(date) {
  return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
  1. date checks whether the parameter was not a falsy value (undefined, null, 0, "", etc..)
  2. date检查参数是否不是一个falsy值(无定义、null、0、""等)。
  3. Object.prototype.toString.call(date) returns a native string representation of the given object type - In our case "[object Date]". Because date.toString() overrides its parent method, we need to .call or .apply the method from Object.prototype directly which ..
    • Bypasses user-defined object type with the same constructor name (e.g.: "Date")
    • 绕过具有相同构造函数名的用户定义对象类型(例如:“Date”)
    • Works across different JS contexts (e.g. iframes) in contrast to instanceof or Date.prototype.isPrototypeOf.
    • 与instanceof或Date.prototype.isPrototypeOf相比,可以跨不同的JS上下文(例如iframe)工作。
  4. call(date)返回给定对象类型的本机字符串表示形式——在我们的示例中是“[对象日期]”。因为date.toString()覆盖了其父方法,所以我们需要从Object中调用或.apply方法。原型直接. .通过使用相同的构造函数名(例如:“Date”),通过不同的JS上下文(例如:iframe)来处理用户定义的对象类型,与instanceof或date.t . isprototypeof相比。
  5. !isNaN(date) finally checks whether the value was not an Invalid Date.
  6. !isNaN(date)最终检查该值是否为无效日期。

#7


4  

UnderscoreJS and Lodash have a function called .isDate() which appears to be exactly what you need. It's worth looking at their respective implementations: Lodash isDate, UnderscoreJs

UnderscoreJS和Lodash有一个名为. isdate()的函数,它似乎正是您所需要的。值得关注的是它们各自的实现:Lodash isDate和UnderscoreJs

#8


3  

You could check if a function specific to the Date object exists:

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

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

#9


2  

The best way I found is:

我发现的最好的方法是:

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

#10


1  

This function will return true if it's Date or false otherwise:

如果是日期,则返回true;否则返回false:

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

#11


1  

Also you can use short form

你也可以用简短的表格。

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

or something like this:

或者是这样的:

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

#12


1  

I have been using a much simpler way but am not sure if this is only available in ES6 or not.

我使用了一种更简单的方法,但我不确定这是否只能在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"

However, this will not work on null or undefined since they have no constructor.

但是,这对null或undefined都不起作用,因为它们没有构造函数。

#13


0  

Actually date will be of type Object. But you can check if the object has getMonth method and if it is callable.

实际上date类型为Object。但是您可以检查对象是否有getMonth方法,如果它是可调用的。

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

#14


0  

Yet another variant:

另一个变体:

Date.prototype.isPrototypeOf(myDateObject)

#15


-1  

Couldn't you just use

你不能使用

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

#1


777  

As an alternative to duck typing via

作为一种替代方法,通过

typeof date.getMonth === 'function'

you can use the instanceof operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string') is also instance of Date

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

date instanceof Date

This will fail if objects are passed across frame boundaries.

如果跨框架边界传递对象,则会失败。

A work-around for this is to check the object's class via

解决这个问题的方法是通过检查对象的类

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

#2


85  

You can use the following code:

您可以使用以下代码:

(myvar instanceof Date) // returns true or false

#3


36  

The function is getMonth(), not GetMonth().

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

Anyway, you can check if the object has a getMonth property by doing this. It doesn't necessarily mean the object is a Date, just any object which has a getMonth property.

无论如何,通过这样做,您可以检查对象是否具有getMonth属性。它并不一定意味着对象是日期,只是任何具有getMonth属性的对象。

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

#4


15  

For all types I cooked up an Object prototype function. It may be of use to you

对于所有类型,我都设计了一个对象原型函数。这可能对你有用

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;
}

Now you can check any type like this:

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

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

[Edit march 2013] based on progressing insight this is a better method:

[编辑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

#5


15  

As indicated above, it's probably easiest to just check if the function exists before using it. If you really care that it's a Date, and not just an object with a getMonth() function, try this:

如上所述,在使用函数之前,最好检查函数是否存在。如果您真的关心它是一个日期,而不是一个具有getMonth()函数的对象,请尝试以下方法:

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

This will create either a clone of the value if it's a Date, or create an invalid date. You can then check if the new date's value is invalid or not.

如果值是日期,则创建该值的克隆,或者创建无效的日期。然后可以检查新日期的值是否无效。

#6


8  

In order to check if the value is a valid type of the standard JS-date object, you can make use of this predicate:

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

function isValidDate(date) {
  return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
  1. date checks whether the parameter was not a falsy value (undefined, null, 0, "", etc..)
  2. date检查参数是否不是一个falsy值(无定义、null、0、""等)。
  3. Object.prototype.toString.call(date) returns a native string representation of the given object type - In our case "[object Date]". Because date.toString() overrides its parent method, we need to .call or .apply the method from Object.prototype directly which ..
    • Bypasses user-defined object type with the same constructor name (e.g.: "Date")
    • 绕过具有相同构造函数名的用户定义对象类型(例如:“Date”)
    • Works across different JS contexts (e.g. iframes) in contrast to instanceof or Date.prototype.isPrototypeOf.
    • 与instanceof或Date.prototype.isPrototypeOf相比,可以跨不同的JS上下文(例如iframe)工作。
  4. call(date)返回给定对象类型的本机字符串表示形式——在我们的示例中是“[对象日期]”。因为date.toString()覆盖了其父方法,所以我们需要从Object中调用或.apply方法。原型直接. .通过使用相同的构造函数名(例如:“Date”),通过不同的JS上下文(例如:iframe)来处理用户定义的对象类型,与instanceof或date.t . isprototypeof相比。
  5. !isNaN(date) finally checks whether the value was not an Invalid Date.
  6. !isNaN(date)最终检查该值是否为无效日期。

#7


4  

UnderscoreJS and Lodash have a function called .isDate() which appears to be exactly what you need. It's worth looking at their respective implementations: Lodash isDate, UnderscoreJs

UnderscoreJS和Lodash有一个名为. isdate()的函数,它似乎正是您所需要的。值得关注的是它们各自的实现:Lodash isDate和UnderscoreJs

#8


3  

You could check if a function specific to the Date object exists:

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

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

#9


2  

The best way I found is:

我发现的最好的方法是:

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

#10


1  

This function will return true if it's Date or false otherwise:

如果是日期,则返回true;否则返回false:

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

#11


1  

Also you can use short form

你也可以用简短的表格。

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

or something like this:

或者是这样的:

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

#12


1  

I have been using a much simpler way but am not sure if this is only available in ES6 or not.

我使用了一种更简单的方法,但我不确定这是否只能在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"

However, this will not work on null or undefined since they have no constructor.

但是,这对null或undefined都不起作用,因为它们没有构造函数。

#13


0  

Actually date will be of type Object. But you can check if the object has getMonth method and if it is callable.

实际上date类型为Object。但是您可以检查对象是否有getMonth方法,如果它是可调用的。

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

#14


0  

Yet another variant:

另一个变体:

Date.prototype.isPrototypeOf(myDateObject)

#15


-1  

Couldn't you just use

你不能使用

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