4

I'm having hard time converting a given local date (which is in IST) to GMT using Java 8 classes LocalDateTime and ZonedDateTime.

Consider the following code snippet.

LocalDateTime ldt = LocalDateTime.parse("22-1-2015 10:15:55 AM", DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss a"));

ZonedDateTime gmtZonedTime = ldt.atZone(ZoneId.of("GMT+00"));

System.out.println("Date (Local) : " + ldt);

System.out.println("Date (GMT) : " + gmtZonedTime);

Which produces the following output:

Date (Local) : 2015-01-22T10:15:55
Date (GMT) : 2015-01-22T10:15:55

As I perceive this, it is only converting the format, not the time.

The output I expect is this: (As GMT is 5.30 hours behind IST, for instance)

Date (Local) : 2018-02-26T01:30
Date (GMT) : 2018-02-26T08:00Z[GMT]

Please guide me get there!

Aryan Venkat
  • 679
  • 1
  • 10
  • 34
  • 2
    If you look closely in your code, you haven't mentioned the delay of `5:30` anywhere. Your `ZonedDateTime` is supposed to have that data. – Alanpatchi Feb 26 '18 at 08:51

2 Answers2

4
LocalDateTime ldt = LocalDateTime.parse("22-1-2015 10:15:55 AM",
            DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss a"));

Instant instant = ldt.atZone(ZoneId.of("GMT+05:30")).toInstant(); // get instant in timeLine by mentioning the zoneId at which you have obtained the ldt

System.out.println("Date (Local) : " + ldt);

System.out.println("Date (GMT) : " + LocalDateTime.ofInstant(instant, ZoneId.of("GMT")));
Alanpatchi
  • 1,177
  • 10
  • 20
  • 2
    I think your answer is right, but you should explain what you are doing. – IQV Feb 26 '18 at 08:38
  • Worked like a charm. I just changed it to consider system's default timezone. `Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();` – Aryan Venkat Feb 26 '18 at 09:55
4

The output is what you should expect. A LocalDateTime does not have a time zone at all, it just has the date and time somewhere (not specified). Your assumption that it is in IST is wrong, it is not. The atZone method adds a time zone, in this case UTC/GMT, but it does not change the date or time.

See https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html.

You probably want to convert the LocalDateTime to a ZonedDateTime for IST first and then change the time zone to UTC. That should change the time.

ewramner
  • 5,810
  • 2
  • 17
  • 33