0

I have written a function to check whether a string is date string or not. Here's my function.

function isDate(dateString) {var dateObject = new Date(dateString);
    return ((dateObject) !== "Invalid Date" && !isNaN(dateObject)) ? true : false;
}

It gives following results.

isDate("12345");// return true
isDate("temp");//return false
isDate("temp - 123456");// return true

In the last case I don't know why it is not giving me false. Please help.

Jeroen
  • 1,168
  • 1
  • 12
  • 24
Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71
  • Why not use `Date.parse()` ? – Swaraj Giri Jul 01 '15 at 06:59
  • All three cases should return false... even the first case. Are you sure this is the code that you used? – light Jul 01 '15 at 07:01
  • On which browser are you testing it? – haim770 Jul 01 '15 at 07:02
  • that is because `new Date("temp - 123456")` is parsing the string – Arun P Johny Jul 01 '15 at 07:05
  • @ArunPJohny Obviously. But how is it parsing it to conclude that result? – CodingIntrigue Jul 01 '15 at 07:06
  • @RGraham because `"12345"` is a string, not a number. If you pass a number, it gets interpreted as milliseconds since 1970 Jan 1. If you pass a string, it gets interpreted as a date string. – light Jul 01 '15 at 07:08
  • @light Right. It seems that whatever method is parsing is just looking for any year value first – CodingIntrigue Jul 01 '15 at 07:09
  • @OP - Not an answer, but bottom line is your test for a date is invalid. You can't have a parser which understands all date/formats. You need to put some restrictions on the input string. Using Regex to match a given format first would be a good start. This is also a good reason to [read the comments on answers](http://stackoverflow.com/questions/7445328/check-if-a-string-is-a-date-value#comment-49738547) before using copy/paste :) – CodingIntrigue Jul 01 '15 at 07:16
  • that last one _is_ a date string, at least in the very forgiving V8 core – dandavis Jul 01 '15 at 07:21
  • @All I have created the fillde for it http://jsfiddle.net/hitesh_kumar/8uaeesu2/ Please update the fiddle and make it working as expected. – Hitesh Kumar Jul 01 '15 at 08:37

0 Answers0