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 with the java.time classes built into Java 8 and later.
Your example data does not match the format shown in your example code. One uses SOLIDUS (slash) character, the other uses COLON character. I'll go with COLON.
DateTimeFormatter
Define a formatting pattern to match the input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MM:uuuu" );
LocalDate
Parse as a LocalDate
object as the input has no time-of-day and no time zone.
LocalDate localDateGood = LocalDate.parse( "27:03:2010" , f );
System.out.println( "localDateGood: " + localDateGood );
Now try some bad input. Trap for the appropriate exception.
try {
LocalDate localDateBad = LocalDate.parse( "40:03:2010" , f );
} catch ( DateTimeParseException e ) {
System.out.println( "ERROR - Bad input." );
}
See this code run live in IdeOne.com.
localDateGood: 2010-03-27
ERROR - Bad input.
ISO 8601
Use standard ISO 8601 formats when exchanging/storing date-time values as text. The standard formats are sensible, practical, easily read by humans of various cultures, and easy for machines to parse.
For a date-only value the standard format is YYYY-MM-DD such as 2010-03-27
.
The java.time classes use standard ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern at all.
LocalDate localDate = LocalDate.parse( "2010-03-27" );
String output = localDate.toString(); // 2010-03-27
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.