首页 文章

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

提问于
浏览
427

我在网页上有一个恼人的错误:

date.GetMonth()不是函数

所以,我想我做错了什么 . 变量 date 不是 Date 类型的对象 . How can I check for a datatype in Javascript? 我试图添加 if (date) ,但它不起作用 .

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

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

谢谢!

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

15 回答

  • 6

    如上所述,'s probably easiest to just check if the function exists before using it. If you really care that it'是Date,而不仅仅是具有 getMonth() 函数的对象,请尝试以下方法:

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

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

  • 3

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

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

    作为鸭子打字的替代品

    typeof date.getMonth === 'function'
    

    你可以使用 instanceof 运算符,即它也会因无效日期而返回true,例如 new Date('random_string') 也是Date的实例

    date instanceof Date
    

    如果对象跨帧边界传递,则会失败 .

    解决方法是通过检查对象的类

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

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

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

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

  • 3

    如果是Date,则此函数将返回 true ,否则返回 false

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

    我找到的最好方法是:

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

    您也可以使用简短形式

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

    或类似的东西:

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

    你能不能用

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

    您可以使用以下代码:

    (myvar instanceof Date) // returns true or false
    
  • 36

    对于所有类型,我都编写了一个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
    

    [ Edit march 2013 ]基于进步的洞察力,这是一个更好的方法:

    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
    
  • 1

    UnderscoreJS和Lodash有一个名为.isDate()的功能,它看起来正是你所需要的 . 值得一看的是它们各自的实现:Lodash isDateUnderscoreJs

  • 16

    该函数是 getMonth() ,而不是 GetMonth() .

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

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

    另一个变种:

    Date.prototype.isPrototypeOf(myDateObject)
    
  • 0

    实际上日期的类型为 Object . 但是你可以检查对象是否有 getMonth 方法以及它是否可调用 .

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

相关问题