Answers:
作为通过鸭子输入的替代方法
typeof date.getMonth === 'function'
您可以使用instanceof运算符,即,但是对于无效日期也将返回true,例如new Date('random_string'),也是Date的实例
date instanceof Date
如果对象跨越帧边界传递,则将失败。
一种解决方法是通过检查对象的类
Object.prototype.toString.call(date) === '[object Date]'
window或self)中是局部的;不同的框架具有自己的全局对象,并且它们的属性(即全局变量)引用不同的对象:Dateframe1中的功能对象不同于frame2中的功能对象Date;也是这样Date.prototype,这是instanceof失败的原因:Date.prototypefrom frame1不属于Dateframe2实例的原型链的一部分
new Date('something') instanceof Datetrue在Chrome中返回。那将行不通。
您可以使用以下代码:
(myvar instanceof Date) // returns true or false
instanceof触发错误否定的演示:jsbin.com/vufufoq/edit?html
为了检查该值是否是标准JS-date对象的有效类型,可以使用以下谓词:
function isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
date检查参数是否不是falsy值(undefined,null,0,""等。)Object.prototype.toString.call(date)返回给定对象类型的本机字符串表示形式-在我们的例子中"[object Date]"。由于date.toString()它的父类的方法覆盖,我们需要.call或.apply从方法Object.prototype直接从..。
instanceof或相比,可跨不同的JS上下文(例如iframe)工作Date.prototype.isPrototypeOf。!isNaN(date)最后检查该值是否不是Invalid Date。isNaN可以用来检查Date。那就是PHP的等级限制。
typeof Date.now() === "number",但是:typeof new Date() === "object"。但是,更现实的是,日期是时间和空间中的位置。
如上所述,最简单的方法是在使用该功能之前先检查该功能是否存在。如果您真的关心它是一个Date,而不仅仅是具有getMonth()函数的对象,请尝试以下操作:
function isValidDate(value) {
var dateWrapper = new Date(value);
return !isNaN(dateWrapper.getDate());
}
这将创建值的克隆(如果是)Date,或者创建无效的日期。然后,您可以检查新日期的值是否无效。
Object.prototype.toString.call(value) === '[object Date]'如果可能会得到数字,您可能想使用接受的答案()。此答案中的方法确实告诉您能否将value转换为Date。
对于所有类型,我都编写了对象原型函数。它可能对您有用
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
UnderscoreJS和Lodash有一个调用的函数.isDate()这似乎正是你所需要的。这是值得看各自的实现:Lodash而isDate,UnderscoreJs
我发现的最好方法是:
!isNaN(Date.parse("some date test"))
//
!isNaN(Date.parse("22/05/2001")) // true
!isNaN(Date.parse("blabla")) // false
我一直在使用一种简单得多的方法,但是不确定这是否仅在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"也会返回,这与检查参数是否具有getMonth属性一样危险。
true如果是日期,则返回此函数false:
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
isDate(new (function AnythingButNotDate(){ })())返回true
另一个变体:
Date.prototype.isPrototypeOf(myDateObject)
instanceof。
iWindow.Date.prototype.isPrototypeOf(iWindow.date); // true iWindow.date instanceof iWindow.Date; // true
一种使用try / catch的方法
function getFormatedDate(date = new Date()) {
try {
date.toISOString();
} catch (e) {
date = new Date();
}
return date;
}
console.log(getFormatedDate());
console.log(getFormatedDate('AAAA'));
console.log(getFormatedDate(new Date('AAAA')));
console.log(getFormatedDate(new Date(2018, 2, 10)));
实际上,日期将是类型Object。但是您可以检查对象是否具有getMonth方法以及是否可调用。
function getFormatedDate(date) {
if (date && date.getMonth && date.getMonth.call) {
var month = date.getMonth();
}
}
function Date() {/*...*/}也是Date。即简单地比较构造函数会容易出错,这通常会导致误报。使用stackoverflow.com/a/44198641/5846045
你不能只用
function getFormatedDate(date) {
if (date.isValid()) {
var month = date.GetMonth();
}
}
isValid方法
isValid。只有moment.js具有这样的API。
Invalid Date:stackoverflow.com/a/44198641/5846045