Check if the given string is a date object

I need to check if a given string is a date object or not.

I originally used

Date.parse(val) 

If you check Date.parse("07/28/2014 11:23:29 AM") , this will work.
But if you check Date.parse("hi there 1") , this will work too, which should not.

So, I changed my logic to

 val instanceof Date 

But for my string with a date of date "07/28/2014 11:23:29 AM" instanceof Date it returns false .

So, is there a way by which I can properly check my string for Date?

+6
source share
2 answers

You can use Date.parse to check if it is a date or not using the code below. 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 ()

+4
source
 function isDate(val) { var d = new Date(val); return !isNaN(d.valueOf()); } 

Hope helps you

+1
source

Source: https://habr.com/ru/post/972940/


All Articles