No need for regex
Java has an industry-leading set of classes for date-time handling, found in the java.time package. Let them handle parsing of your input strings rather than messing with regex.
java.time
The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes (Date
, Calendar
, SimpleDateFormat
).
Define a formatting pattern to match your input strings.
String input = "20180123123456" ; // yyyymmddhhmmss
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
Parse as a LocalDateTime
because your input lacks any indication of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2018-01-23T12:34:56
To trap for invalid input, catch DateTimeParseException
.
String input = "20180123123456" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
LocalDateTime ldt = null;
try {
ldt = LocalDateTime.parse( input , f );
} catch ( DateTimeParseException e ) {
System.out.println( "ERROR - invalid input for date-time. input: " + input ) ;
e.printStackTrace(); // Handle invalid input.
}
By the way, be aware that without the context of a time zone or offset-from-UTC, your input string and the LocalDateTime
do not represent a specific moment, and are not a point on the timeline. They represent potential moments along a range of about 26-27 hours (the min/max range of time zone offsets).
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.