Check date in JavaScript

Viewed 19192

I get three variables through a user input, that contain the year of a date, the month and the day. I've already checked if the month var is between 1–12 and so on.

Now I want to check if it's a real date and not a date that doesn't exist like 31–06–2011.

My first idea was to make a new Date instance:

var year = 2011;
var month = 5; // five because the months start with 0 in JavaScript - June
var day = 31;
var myDate = new Date(2011,5,31);
console.log(myDate);

But myDate doesn't return false, because it's not a valid date. Instead it returns 'Fri Jul 01 2011 [...]'.

Any ideas how I can check for an invalid date?

5 Answers

This is a old question question however to help me and other after me, here is a php checkdate solution from the following webpage:

https://locutus.io/php/datetime/checkdate/

function checkdate (m, d, y) {
    return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0))
    .getDate()
}
Related