10

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.

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.

So, is there any way with which I can appropriately validate my string against Date?

PrashantJ
  • 437
  • 1
  • 3
  • 9

2 Answers2

9

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' -

var date = Date.parse(val);
if(isNaN(date))
 alert('This is not date');
else
 alert('This is date object');

For more information - Date Parse()

Naveen Kumar Alone
  • 7,360
  • 5
  • 34
  • 53
Bhushan Kawadkar
  • 27,908
  • 5
  • 34
  • 57
  • 3
    isNaN(Date.parse("hi there 1")) returns `false`! – PrashantJ Jul 28 '14 at 06:39
  • Yes it is return false because `hmm 1` is taking as hour minute formate string and `Date.parse` is converting it to date number. This case also fails with `new Date(val)` for which you accepted answer, see [this](http://jsfiddle.net/E6t4L/8/) – Bhushan Kawadkar Jul 28 '14 at 07:03
  • 2
    won't a number return a number though? "89" is not a date – deebs Apr 22 '16 at 18:51
2
function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

Hope helps you

jgillich
  • 63,850
  • 5
  • 53
  • 80
Neeraj Dubey
  • 4,333
  • 8
  • 27
  • 47