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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With