Check range with java Date and SimpleDateFormat

Hi guys, I would like to know if there is a Date exception that I can handle when I try to parse a date using this code here:

try{
   SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
   Date date = df.parse(dateRelease);
}catch (ParseException e) {} 

Well, if "dateRelease" is not in the correct format, it throws a ParseException, but I want to get if someone writes "40/03/2010" - WRONG with an invalid range of day, month or year. In fact, when an incorrect date is sent, SimpleDateFormat simply creates a new date with default numbers.

Do I have to create my own regular expression method to handle it, or is there an existing exception that tells me that it breaks?

+3
source share
2 answers

Make it non-soft SimpleDateFormat#setLenient()with meaning false.

SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy"); 
df.setLenient(false);
Date date = df.parse(dateRelease);

Then it will throw ParseExceptionwhen the date is not in the valid range.

+5
source

TL; DR

try {
    LocalDate localDate = LocalDate.parse( 
        "40:03:2010" ,    // "40:03:2010" is bad input, "27:03:2010" is good input.
        DateTimeFormatter.ofPattern( "dd:MM:uuuu" )
    ) ;
} catch ( DateTimeParseException e ) {// Invalid input detected.
}

Using java.time

The modern way is to use the java.time classes built into Java 8 and later.

The data in your example does not match the format shown in your sample code. One uses the SOLIDUS character (slash), and the other uses the COLON character. I will go with the COLUMN.

DateTimeFormatter

Define a formatting pattern that matches the input line.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MM:uuuu" );

LocalDate

Disassemble as an object LocalDate, since the entrance has no time of day and does not have a time zone.

LocalDate localDateGood = LocalDate.parse( "27:03:2010" , f );
System.out.println( "localDateGood: " + localDateGood );

Now try typing the wrong entry. Trap for the corresponding exception.

try {
    LocalDate localDateBad = LocalDate.parse( "40:03:2010" , f );
} catch ( DateTimeParseException e ) {
    System.out.println( "ERROR - Bad input." );
}

IdeOne.com.

localDateGood: 2010-03-27

- .

ISO 8601

ISO 8601 / . , , .

YYYY-MM-DD, 2010-03-27.

java.time ISO 8601 / . .

LocalDate localDate = LocalDate.parse( "2010-03-27" );
String output = localDate.toString();  // 2010-03-27

java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .

+1

Source: https://habr.com/ru/post/1778645/


All Articles