Try parsing with each expected format
When you have inputs of various formats, if those formats are mutually exclusive (not ambiguous for one another), simply try parsing each known possible format until one works. When a parsing attempt fails, catch the Exception thrown and try parsing with the next format.
For more information on parsing a string into a date-only object, see How can I change the date format in Java? and many other posts already made on Stack Overflow. Here's a brief example of code.
First, define and collect a series of formatters for each expected format.
Locale locale = Locale.UK ;
List<DateTimeFormatter> formatters = new ArrayList<>( 4 );
formatters.add( DateTimeFormatter.ofPattern( "dd-MMM-uu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd-MM-uu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd/MM/uuuu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" , locale ) ) ;
Try each formatter successively until one succeeds.
LocalDate ld = null ;
for( DateTimeFormatter f : formatters ) {
try{
ld = LocalDate.parse( input , f );
break ; // End this 'for' loop. We succeeded in parsing, so no need to try more formatters.
} catch ( DateTimeParseException e ) {
// Swallow this exception as we expect it when trying a series of formatters.
}
}
Test to see if all the formatters failed to parse. This means we received an input of unexpected format, an error situation.
if( null == ld ) { // All the formatters were tried but failed.
… // Deal with unexpected input.
}
Generate a new String as your output using DateTimeFormatter
. Consider using the ofLocalized…
method rather than specify a particular format.
ISO 8601
Personally, I recommend against ever using a two-digit year. That causes no end of confusion being ambiguous with the month and day-of-month. Memory is cheap enough, and screens big enough, that we can easily afford the bits and pixels to support the luxury of 4-digit years.
Also, consider avoiding your patterns entirely. For data exchange, use only the standard ISO 8601 formats. For a date only that would be YYYY-MM-DD such as 2017-01-23
.
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?
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.