javascript 检查给定的字符串是否是日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24989511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if the given string is a date object
提问by PrashantJ
I need to check whether the given string is date object or not.
我需要检查给定的字符串是否是日期对象。
Initially I used
最初我用
Date.parse(val)
If you check Date.parse("07/28/2014 11:23:29 AM")
, it'll work.
But if you check Date.parse("hi there 1")
, it'll work too, which shouldn't.
如果你检查Date.parse("07/28/2014 11:23:29 AM")
,它会工作。
但是,如果您检查Date.parse("hi there 1")
,它也会起作用,但不应该。
So I changed my logic to
所以我改变了我的逻辑
val instanceof Date
But for my above date string, "07/28/2014 11:23:29 AM" instanceof Date
it returns false
.
但是对于我上面的日期字符串,"07/28/2014 11:23:29 AM" instanceof Date
它返回false
.
So, is there any way with which I can appropriately validate my string against Date?
那么,有什么方法可以根据日期适当地验证我的字符串吗?
回答by Bhushan Kawadkar
You can use Date.parse
to check if it is a date or not using below code. Date.parse()
return number if valid date otherwise 'NaN' -
您可以使用Date.parse
以下代码来检查它是否是日期。Date.parse()
如果有效日期则返回数字,否则为 'NaN' -
var date = Date.parse(val);
if(isNaN(date))
alert('This is not date');
else
alert('This is date object');
For more information - Date Parse()
欲了解更多信息 -日期解析()
回答by Neeraj Dubey
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
Hope helps you
希望能帮到你