Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to convert a given Local Date to GMT Date using Java 8 [duplicate]

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!

like image 723
Aryan Venkat Avatar asked Jan 28 '23 14:01

Aryan Venkat


1 Answers

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.

like image 63
ewramner Avatar answered Jan 31 '23 03:01

ewramner