2

We receive datetime elements relative to the UTC time like 2004-04-12T13:20:00Z.

And we would like to output the datetime in the local datetime, that is expressed with an offset relative to the UTC time like 2004-04-12T12:20:00-01:00.

V Joe
  • 271
  • 1
  • 5
  • 23
  • Go through http://stackoverflow.com/questions/12487125/java-how-do-you-convert-a-utc-timestamp-to-local-time. Hope you get the right answer.. – vineeth Mar 10 '17 at 09:04
  • The Java 8 date and time classes are perfect for this (much better than oldfashioned `SimpleDateFormat` and `Calendar`). Can you use Java 8? – Ole V.V. Mar 10 '17 at 09:11

4 Answers4

7

With the Java 8 date and time classes this is straightforward. Only catch is, we need to go through ZoneDateTime if we want to pick om the computer’s default time zone, and then on to OffsetDateTime to get the output format you requested (another option would be formatting the date and time using a specific DateTimeFormatter; now I am relying on OffsetDateTime.toString()).

    String utcTime = "2004-04-12T13:20:00Z";
    OffsetDateTime dateTimeWithOffset = Instant.parse(utcTime).atZone(ZoneId.systemDefault()).toOffsetDateTime();
    System.out.println(dateTimeWithOffset);

On my computer the above prints

2004-04-12T14:20+01:00

In the answer and the code I have on purpose avoided the term “local date-time” that you used in the question. This is to avoid confusion with the class LocalDateTime, which is used for a date and time without any time zone or offset information.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Good answer. I suggest changing the name of you `localtime` var to something like `offsetDateTime` and point out the orignal poster’S misunderstanding of the term "local". – Basil Bourque Mar 10 '17 at 11:36
1

Use ZonedDateTime from the java 8 API.

ZonedDateTime.ofInstant(Instant.parse("2004-04-12T13:20:00Z"), ZoneId.of("CET"))

it will give you 2004-04-12T15:20+02:00[CET]

Jérôme
  • 1,254
  • 2
  • 20
  • 25
-1

Hope the below solution works.

String date_s = "2004-04-12T13:20:00Z"; 
    SimpleDateFormat dt = new SimpleDateFormat("yyyyy-MM-dd'T'HH:mm:ss'Z'"); 
    Date date = dt.parse(date_s); 

     Calendar cal = Calendar.getInstance(); // creates calendar
        cal.setTime(date); // sets calendar time/date
        cal.add(Calendar.HOUR, 1); // adds one hour (do any offset that you want here)
        String out = dt.format(cal.getTime());
        System.out.println(out.substring(1));
Anirudh
  • 437
  • 2
  • 10
-1

Using the Java 8 JDK, you can use the java.time.Instant class to refer to UTC time. and the folloowing classes for the offset times :

java.time.LocalDate java.time.LocalTime java.time.LocalDateTime

Example :

Instant instant = Instant.now();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.ofOffset("MyZoneId", ZoneOffset.ofHours(3)));
klonq
  • 3,535
  • 4
  • 36
  • 58