6

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.

Saravana
  • 12,647
  • 2
  • 39
  • 57
GOPI
  • 71
  • 2
  • 3
  • 8

3 Answers3

2

I will assume you have the original date as a string. Do the following:

  • Create a SimpleDateFormat and set the timezone to "GMT+14"
  • Parse the string value. You get a Date object
  • Set the timezone of the SimpleDateFormat to "UTC" (or use a different SimpleDateFormat instance)
  • Format the date (if you want the result as a string as well)

Example:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ConvertToUTC {
  public static void main(String[] args) throws Exception {

      String dateval = "2016-12-21T07:48:36";
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      df.setTimeZone(TimeZone.getTimeZone("GMT+14"));
      Date date = df.parse(dateval);

      System.out.println(df.format(date)); // GMT+14

      df.setTimeZone(TimeZone.getTimeZone("UTC"));
      System.out.println(df.format(date)); // UTC
  }
}
Grodriguez
  • 21,501
  • 10
  • 63
  • 107
  • Whether day light saving component will be considered if we use GMT+offset instead of UTC+offset? – GOPI Dec 21 '16 at 19:39
  • @GOPI The answer is correct. Your question only mentions fixed offsets (and it is equal if the prefix is GMT or UTC). So day-light-saving is irrelevant in the context of your question. Otherwise don't use fixed offsets but timezone identifiers like "Asia/Tokyo" etc. – Meno Hochschild Dec 21 '16 at 20:15
  • Thanks Meno & Grodriguez! – GOPI Dec 21 '16 at 21:55
2

use "GMT+14:00" instead of "UTC+14:00"

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT+14:00"));
final Date d = f.parse("2016-12-21T07:48:36");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(d)); // -> 2016-12-20T05:48:36
Sxilderik
  • 796
  • 6
  • 20
2

tl;dr

LocalDateTime.parse( "2016-12-21T07:48:36" )        // Parse as a `LocalDateTime` given the lack of an offset or zone. *Not* an actual moment, only a rough approximation of potential moments along a range of about 26-27 hours.
             .atOffset( ZoneOffset.ofHours( 14 ) )  // Assign an offset-from-UTC as context, giving meaning to determine an actual point on the timeline.
             .toInstant()                           // Renders `Instant` object in UTC.

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.

ZoneOffset offset = ZoneOffset.ofHours( 14 ); // fourteen hours ahead of UTC.

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.

LocalDateTime ldt = LocalDateTime.parse( "2016-12-21T07:48:36" );

Apply the offset to the local date-time to get an OffsetDateTime an object.

OffsetDateTime odt = ldt.atOffset( offset );

From that, extract an Instant which is always in UTC.

Instant instant = odt.toInstant();

instant.toString(): 2016-12-20T17:48:36Z

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Technically an `Instant` is not "in" any timezone. It represents an offset from the epoch. – OrangeDog Dec 21 '16 at 18:13
  • 2
    @OrangeDog Incorrect. An `Instant` is most certainly in UTC. To quote the class doc: “The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z”. That `Z` is short for Zulu and means UTC. Without being defined as UTC an `Instant` would have no meaning. – Basil Bourque Dec 21 '16 at 18:19
  • Just because the representation of the epoch in the docs is in Z, doesn't mean that an `Instant` is. To quote the class doc: "this Java API defines its own time-scale, the Java Time-Scale". – OrangeDog Dec 21 '16 at 18:22
  • 1
    We can also say: An `Instant` is anchored arithmetically on UTC-offset zero (absolutely necessary for any internal date-time-calculation), but for formatting purposes, an instant should never be used without a timezone or offset for representing local informations, and the `java.time`-API prevents this i.e. forces the user to specify a timezone or offset when formatting/parsing an instant (in most cases). – Meno Hochschild Dec 21 '16 at 19:01