Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch does not catch invalid date [duplicate]

I am trying to validate a date input, so if it is correct, I handle one way, and if invalid, I handle another...

var date, datestring, e;

datestring = "2012-03-222";

try {
  date = new Date(datestring);
  /* Ends up logging `Invalid Date`
  */

  console.log(date);
} catch (_error) {
  e = _error;
  /* Should come here and log `Error: Invalid Date` or the likes
  */

  console.log("Erorr: " + e);
}

I could just check the returned string, and see if it is Invalid Date or not, but am both surprised that try/catch does not work for this scenario, and concerned that there might be other error messages I do not match.

How should I handle this problem?

like image 406
Billy Moon Avatar asked Apr 03 '13 16:04

Billy Moon


People also ask

Why invalid date JavaScript?

The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date. parse() .

How does angular handle invalid date?

You need a valid date object in order to use date transformations. The string you have is not a valid date string so you either have to provide a valid date string that you can use, or simply use string manipulation to do what you want.

How do you check if a string is a valid date in JavaScript?

If the variables are of Date object type, we will check whether the getTime() method for the date variable returns a number or not. The getTime() method returns the total number of milliseconds since 1, Jan 1970. If it doesn't return the number, it means the date is not valid.


1 Answers

Date objects do not throw an error if they are invalid. There is a method described in this related question that will determine if a date is valid.

like image 187
Michael Pratt Avatar answered Sep 30 '22 00:09

Michael Pratt