tl;dr
LocalDateTime.parse(
"2016-01-02 12:34:56".replace( " " , "T" )
)
Using java.time
The Answer by MadProgrammer is correct: Wrong code used in formatting pattern. But there is an even easier and better approach.
You are using troublesome old date-time classes now supplanted by the java.time classes.
Your input format in almost in standard ISO 8601 format. Just replace the SPACE in middle with a T
.
String input = "2016-01-02 12:34:56".replace( " " , "T" );
The java.time classe use ISO 8601 formats by default. So need to specify a formatting pattern at all, so no formatting codes to get wrong.
LocalDateTime ldt = LocalDateTime.parse( input );
We parse as a LocalDateTime
because the input lacks information about offset-from-UTC or time zone. If this value was meant for UTC, apply an offset to get an OffsetDateTime
.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
If meant for some time zone, transform into a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( z );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.