Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - 如何检查对象是否为日期?(How to check whether an object is a date?)

I have an annoying bug in on a webpage:

(我在网页上有一个烦人的错误:)

date.GetMonth() is not a function

(date.GetMonth()不是函数)

So, I suppose that I am doing something wrong.

(因此,我想我做错了什么。)

The variable date is not an object of type Date .

(可变date不是Date类型的对象。)

How can I check for a datatype in Javascript?

(如何检查Javascript中的数据类型?)

I tried to add a if (date) , but it doesn't work.

(我试图添加一个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()的参数的类型为Date 。)

  ask by Martin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an alternative to duck typing via

(作为通过鸭子输入的替代方法)

typeof date.getMonth === 'function'

you can use the instanceof operator, ie But it will return true for invalid dates too, eg 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]'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...