Reputation: 474
I'm trying to check if a date is valid. If I pass 31/02/2018 to new Date it will return Tue Mar 03 1987 00:00:00 GMT+0000 (GMT) as 31/02/2018 is not a real date. So how can I compare the passed date with the return date of new Date? or am I going about this the wrong way altogether.
function isDateValid() {
var dob = "31/02/1994",
isValidDate = false;
var reqs = dob.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2];
var birthday = new Date(year + "-" + month + "-" + day);
if (birthday === "????") {
isValidDate = true;
}
return isValidDate;
}
Upvotes: 0
Views: 65
Reputation: 4866
This is what you are looking for. I left your code unchanged and stuck to your original request.
function isDateValid() {
var dob = "31/02/2018",
isValidDate = false;
var reqs = dob.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2];
var birthday = new Date(year + "-" + month + "-" + day);
if (+year === birthday.getFullYear()&&
+day === birthday.getDate() &&
+month === birthday.getMonth() + 1) {
isValidDate = true;
}
return isValidDate;
}
console.log(isDateValid());
Upvotes: 0
Reputation: 2049
You can get the last day of each month by doing this;
var lastDay = new Date(month, year, 0).getDate();
In your case;
function isDateValid(date){
var isValidDate = false;
var reqs = date.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2],
lastDay = new Date(month, year, 0).getDate();
if(day > 0 && day <= lastDay)
isValidDate = true;
return isValidDate;
}
Upvotes: 2