I am trying to convert local date to UTC by using Joda Time. The code that I used is shown below and it works great.
Date localDate = new Date();
System.out.println("Local Date : " + localDate);
DateTimeZone tz = DateTimeZone.getDefault();
Date utcDate = new Date(tz.convertLocalToUTC(localDate.getTime(), false));
System.out.println("UTC Date : " + utcDate);
Output :
Local Date : Wed May 29 11:54:46 EEST 2013
UTC Date : Wed May 29 08:54:46 EEST 2013
But, if I send UTC Date as a parameter to the DateTimeZone.convertLocalToUTC() method, it also decreases the hour by 3. However, since it is UTC Date, I expect it not to convert date again. Is this a bug or am I missing something?
Date localDate = new Date();
System.out.println("Local Date : " + localDate);
DateTimeZone tz = DateTimeZone.getDefault();
Date utcDate = new Date(tz.convertLocalToUTC(localDate.getTime(), false));
System.out.println("UTC Date : " + utcDate);
Date utcDate2 = new Date(tz.convertLocalToUTC(utcDate.getTime(), false));
System.out.println("UTC Date 2 : " + utcDate2);
Output :
Local Date : Wed May 29 11:54:46 EEST 2013
UTC Date : Wed May 29 08:54:46 EEST 2013
UTC Date 2 : Wed May 29 05:54:46 EEST 2013
As per javadoc of convertLocalToUTC
Converts a local instant to a standard UTC instant with the same local time. This conversion is used after performing a calculation where the calculation was done using a simple local zone.
Methods makes no assumption or validation that passed date is in UTC or not, it always consider passed date as local and converts to UTC. Your program output is correct.
Look at it from the convertLocalToUTC() methods point of view. It just takes a long and a boolean. It does not have any knowledge that the long you are passing it is UTC or not. It assumes that you are passing a long that is local time and adjusts it accordingly.
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