Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date allows invalid data (e.g. Feb 30th) [duplicate]

How to validate a date? I mean not the format, but the logic. For example: Feb 30th is not a valid date.

var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());

Returns 2015-03-01T13:02:49.073Z (March 1st).

But I want a information that this date (input) is not valid.

Edit: Tested in Chrome. Firefox returns "invalid date". But not on parsing. Only when the date is used (e.g. toISOString()) an exception is thrown.

try
{
  var date = new Date("2015-02-29T13:02:49.073Z");
  console.log(date.toISOString());
}
catch(e)
{
    console.log("error: " + e.message);
}

Firefox:

invalid date

Chrome:

(nothing, just switched to the next date.)

Summary: It is browser-dependent. So, not recommended to use.

jsfiddle example

like image 887
Dominik Avatar asked Mar 23 '16 13:03

Dominik


3 Answers

The easiest thing I can think of, is to convert the parsed date to ISO string and compare it to the original input:

var input = "2015-02-29T13:02:49.073Z"
var date = new Date(input);
var isValid = (input === date.toISOString());
like image 154
Jan Avatar answered Nov 14 '22 23:11

Jan


I use this function to check whether a date is valid or not:

function isValidDate(year, month, day) {
    month = month - 1;
    var d = new Date(year, month, day);
    if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
      return true;
    }
    return false;
}
like image 34
Keyne Viana Avatar answered Nov 15 '22 00:11

Keyne Viana


I wrote small function for you:

function check_date(str){
    try{
        return str == new Date(str).toISOString()
    }catch(e){
        return false;
    }
}

Try this

console.log(check_date('2015-02-01T13:02:49.073Z'));
console.log(check_date('2015-02-35T13:02:49.073Z'));
console.log(check_date('2015-02-29T13:02:49.073Z'));

https://jsfiddle.net/8o040ctr/

like image 26
Veniamin Avatar answered Nov 15 '22 01:11

Veniamin