java.time
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
ISO 8601
Your input string nearly complies with the standard ISO 8601 formats. To comply, replace that SPACE with a T
. The java.time classes use standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. If the input is of the date-only type, the replace
has no effect.
String input = "2017-01-23 12:34:56".replace( " " , "T" ) ; // Replace SPACE with `T` to comply with ISO 8601.
String input = "2017-01-23".replace( " " , "T" ) ; // Has no effect.
Various inputs
To handle both the date-only or date-time inputs, either test for length or attempt a parse and trap for exception.
if( input.length() == 10 ) {
LocalDate ld = LocalDate.parse( input ) ;
} else {
LocalDateTime ldt = LocalDateTime.parse( input ) ;
}
Zone/Offset
Note that a LocalDateTime
purposely lacks any offset-from-UTC & time zone. If your situation is known to intend either offset or zone, assign to create an OffsetDateTime
or ZonedDateTime
object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime z = ldt.atZone( z ) ;
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.