TL; DR
LocalDateTime.parse( "2016-12-21T07:48:36" )
java.time
The modern way is the java.time classes built into Java 8 and later. Most of the functionality has been ported to Java 6 and 7 in the ThreeTen-Backport project .
ZoneOffset offset = ZoneOffset.ofHours( 14 ); // fourteen hours ahead of UTC.
Parse the string as LocalDateTime
because it lacks offset or zone information. Your input complies with ISO 8601 , so there is no need to specify a formatting template.
LocalDateTime ldt = LocalDateTime.parse( "2016-12-21T07:48:36" );
Apply the offset to the local date-time to get an OffsetDateTime
object.
OffsetDateTime odt = ldt.atOffset( offset );
From this, extract Instant
, which is always in UTC .
Instant instant = odt.toInstant();
instant.toString (): 2016-12-20T17: 48: 36Z
In UTC , this is a different date, 20th place instead of 21st.
Watch the code in real time at IdeOne.com .
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy datetime classes such as java.util.Date
, Calendar
and SimpleDateFormat
.
The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
Using the JDBC driver compatible with JDBC 4.2 or later, you can exchange java.time objects directly with your database. No need for strings or java.sql. * Classes.
Where to get java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes such as Interval
, YearWeek
, YearQuarter
and more .