Not getting correct timezone in Java 8?

172 views Asked by At

I have set my system data time to Asia/Kolkata and it is:

Date: 2015-06-12
Time: 12:07:43.548

Now i have written following program in Java 8

ZoneId paris = ZoneId.of("Europe/Paris");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInParis  = ZonedDateTime.of(localtDateAndTime, paris );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInParis  );

When i run the code it shows following time for Paris:

Current date and time in a particular timezone :    

2015-06-12T12:07:43.548+02:00[Europe/Paris]

The above Europe/Paris is same as of Asia/Kolkata. Could anyone please explain where i am doing wrong?

Update: I prefer not using class from another Java package; as i have heard that this package java.time have enough functionalities to handle maximum date time jobs and i hope this one is included :)

1

There are 1 answers

3
Jesper On BEST ANSWER

A LocalDateTime is a date and time without a timezone. When you create a ZonedDateTime object out of it, you're explicitly attaching a timezone to the LocalDateTime.

It's not going to convert from your timezone to the Europe/Paris timezone; note that the LocalDateTime does not have a timezone at all; it doesn't know that you mean it to be Asia/Kolkata.

If you want to convert from Kolkata time to Paris time, start with a ZonedDateTime that uses the Asia/Kolkata timezone:

// Current time in Asia/Kolkata
ZonedDateTime kolkata = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

// Convert to the same time in Europe/Paris
ZonedDateTime paris = kolkata.withZoneSameInstant(ZoneId.of("Europe/Paris"));

(edit, thanks JBNizet): If you just want "now" in Europe/Paris time, you can do:

ZonedDateTime paris = ZonedDateTime.now(ZoneId.of("Europe/Paris"));