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?
One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.
There are two possible solutions: Use a SimpleDateFormat and try to convert the String to Date . If no ParseException is thrown the format is correct. Use a regular expression to parse the String.
If you're not sure whether or not it's a date beforehand, don't sweat it. Just wait it out and see when it happens. Often when you arrive, you can tell pretty quickly. If it seems like they've put in some thought and effort for a special setting, chances are it's a date.
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
Hope helps you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With