I have a date time value 2016-12-21T07:48:36 with an offset of UTC+14. How to convert the datetime into equivalent standard GMT time.
I tried with sampleDateFormat.parse()
method.But, I am not able to get the TimeZone object for UTC offset like.
sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC+14:00"))
Please help me to convert the UTC datetime into standard GMT time in Java 7.
tl;dr
java.time
The modern way is with the java.time classes built into Java 8 and later. Much of the functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project.
Parse the string as a
LocalDateTime
as it lacks any info about offset or zone. Your input is in standard ISO 8601 format, so no need to specify a formatting pattern.Apply the offset to the local date-time to get an
OffsetDateTime
an object.From that, extract an
Instant
which is always in UTC.In UTC, the value is a different date, the 20th instead of 21st.
See live code at IdeOne.com.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.