11

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?

1
  • try to replace date string 07/28/2014 11:23:29 AM to 29-07-2014 11:23:29 AM Commented Jul 28, 2014 at 6:30

2 Answers 2

11

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()

Sign up to request clarification or add additional context in comments.

3 Comments

isNaN(Date.parse("hi there 1")) returns false!
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
won't a number return a number though? "89" is not a date
2
function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

Hope helps you

2 Comments

@PrashantJ Can you explain why unmark the answer as accept.Is it not working or something else.
!isNaN(new Date("Hacker%1337")) returns true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.