Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to check a date is valid or not in JavaScript

3 Answers

0 votes
function isValidDate(d) {
    if (Object.prototype.toString.call(d) === "[object Date]") { 
        if (isNaN(d.getTime())) {  
           return false;
        } else { 
              return true;
          } 
    } else {
    	 return false;
    }
}
 
let d1 = new Date(); 
let d2 = new Date(2020, 5, 21); 
let d3 = new Date('2020-555-19'); 
let d4 = new Date(2020, 5, 2222222221, 10, 42, 33);
let d5 = new Date(999999930000);
let d6 = new Date("May 21, 2020 16:53:00");
 
console.log(isValidDate(d1));
console.log(isValidDate(d2));
console.log(isValidDate(d3));
console.log(isValidDate(d4));
console.log(isValidDate(d5));
console.log(isValidDate(d6));
 
 
 
/*
run:
 
true
true
false
false
true
true
 
*/

 



answered May 21, 2020 by avibootz
edited Mar 10, 2022 by avibootz
0 votes
function isValidDate(d) {
    return d instanceof Date && isFinite(d)
}

let d1 = new Date(); 
let d2 = new Date(2020, 5, 21); 
let d3 = new Date('2020-555-19'); 
let d4 = new Date(2020, 5, 2222222221, 10, 42, 33);
let d5 = new Date(999999930000);
let d6 = new Date("May 21, 2020 16:53:00");

console.log(isValidDate(d1));
console.log(isValidDate(d2));
console.log(isValidDate(d3));
console.log(isValidDate(d4));
console.log(isValidDate(d5));
console.log(isValidDate(d6));


/*
run:

true
true
false
false
true
true

*/

 



answered May 21, 2020 by avibootz
0 votes
function isValidDate(d) {
    return d instanceof Date && !isNaN(d);
}

let d1 = new Date(); 
let d2 = new Date(2020, 5, 21); 
let d3 = new Date('2020-555-19'); 
let d4 = new Date(2020, 5, 2222222221, 10, 42, 33);
let d5 = new Date(999999930000);
let d6 = new Date("May 21, 2020 16:53:00");

console.log(isValidDate(d1));
console.log(isValidDate(d2));
console.log(isValidDate(d3));
console.log(isValidDate(d4));
console.log(isValidDate(d5));
console.log(isValidDate(d6));


/*
run:

true
true
false
false
true
true

*/

 



answered May 21, 2020 by avibootz

Related questions

2 answers 129 views
1 answer 179 views
1 answer 112 views
1 answer 129 views
1 answer 1,491 views
...