Using java.time
No magic way to decipher any random format. But in your case you have easy ways to identify each of the particular formats.
DateTimeFormatter f ;
if ( input.contains( "_" ) ) { // 20170112_125645
f = DateTimeFormatter.ofPattern( "uuuuMMdd'_'HH:mm:ss" );
} else if ( input.contains( " " ) ) { // 20170915 137546
f = DateTimeFormatter.ofPattern( "uuuuMMdd' 'HH:mm:ss" );
} else if ( input.contains( ":" ) ) { // 09122017:135292
f = DateTimeFormatter.ofPattern( "ddMMuuuu':'HH:mm:ss" );
} else if ( input.length() == 16 ) { // 2014012014132390
f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmssSS" );
} else {
… // Handle error condition
System.out.println( "ERROR - Unexpected input: " + input ) ;
}
LocalDateTime ldt = LocalDateTime.parse( input , f );
Of course in real code being called many times often, I would cache those DateTimeFormatter
instances rather than instantiate each time. Perhaps define an Enum
if used in various other places in your code base.
Usually I recommend always specifying a Locale
in the formatter rather than rely implicitly on JVM’s current default. But here I don't think the locale has any effects.
Avoid legacy date-time classes
You mentioned SimpleDateFormat
. That class is one of the troublesome old date-time classes that should be avoided. Now legacy, supplanted by the java.time classes.
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.