Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sanity check a date in Java

I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.

How do you check that a date, given as a combination of day, month, and year, is a valid date?

For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.

like image 442
Bloodboiler Avatar asked Oct 22 '08 18:10

Bloodboiler


People also ask

How do you check if a date is a valid date in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019")); This was the most common solution before Java 8.

How do you validate a date in YYYY MM DD format in Java?

Formatting DatesString pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);

How do you check if a date is valid?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.


1 Answers

Key is df.setLenient(false);. This is more than enough for simple cases. If you are looking for a more robust (I doubt) and/or alternate libraries like joda-time then look at the answer by the user "tardate"

final static String DATE_FORMAT = "dd-MM-yyyy";  public static boolean isDateValid(String date)  {         try {             DateFormat df = new SimpleDateFormat(DATE_FORMAT);             df.setLenient(false);             df.parse(date);             return true;         } catch (ParseException e) {             return false;         } } 
like image 52
Aravind Yarram Avatar answered Sep 28 '22 02:09

Aravind Yarram