Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have a javascript in which I will parse the value into datetime format. My codes as below:
var dateEnd = new Date(Date.parse(dateTimeValue));


I want to check if it is invalid date thus I have added the codes as below:
if (Object.prototype.toString.call(dateEnd) !== "[object Date]")
{
alert("Wrong date format");
}


But no matter i enter the correct or wrong format, the alert will prompt. What have I done wrong?

What I have tried:

1. Tried dateTimeValue instanceOf Date but no avail. Get the same result.
Posted
Updated 25-Dec-17 23:51pm

1 solution

You can check if dateEnd.getTime() is NaN (Not a Number). In that case, the date is invalid.
JavaScript
if (isNaN(dateEnd.getTime())) {
    alert("Wrong date format");
}
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 26-Dec-17 7:05am    
5ed.
Jamie888 26-Dec-17 21:21pm    
Thank you sir, it works! I have tried this method too previously but it prompted me "gettime() is not a function" error. Maybe i missed out a bracket. Anyhow, may i know the details on why does my original method don't work? I have tried online for some explanation but could not quite get the answer i was looking for.
Thomas Daniels 27-Dec-17 6:04am    
It's getTime, not gettime. JavaScript is case-sensitive.
Jamie888 28-Dec-17 1:13am    
My bad. Thank you sir for your explanation and for the help. Really appreciate it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900