Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime : Convert local to UTC ambiguity

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
like image 991
Parvin Gasimzade Avatar asked May 29 '13 09:05

Parvin Gasimzade


2 Answers

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.

like image 170
harsh Avatar answered Oct 18 '22 22:10

harsh


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.

like image 29
rgeorge Avatar answered Oct 18 '22 21:10

rgeorge