[threeten-dev] j.u.Date/Calendrical/GregorianCalendar

Masayoshi Okutsu masayoshi.okutsu at oracle.com
Thu Dec 6 21:40:58 PST 2012


On 12/6/2012 7:45 PM, Stephen Colebourne wrote:
> On 6 December 2012 06:36, Masayoshi Okutsu <masayoshi.okutsu at oracle.com> wrote:
>> I agree with Sherman. The new things should be imported into the old ones.
>> But not the other way around.
>>
>> The conversion between java.util.Calendar and 310 is very tricky.
>>
>> java.util.Calendar to 310:
>>
>> How about a similar approach to DateTimeFormatter.parse? Something like
>> this:
>>
>>    public <T> T to(class<T> type)
> This would probably require reflection to implement, so isn't really
> ideal.

I thought it'd be a piece of cake to implement it with 
DateTimeBuilder.build(Class), but it wasn't. I had to take a look at the 
"real documentation" to determine what fields need to be set to produce 
an instance of the given class...

>   I think toInstant() and toZoneDateTime() cover most cases.

But a Calendar isn't always a GregorianCalendar.

I prototyped the method. Here's a demo. :-)

import java.util.*;
import javax.time.*;
import javax.time.chrono.*;
import javax.time.chrono.global.*;

public class To310Test {
     public static void main(String[] args) {
         Calendar cal = Calendar.getInstance();
         LocalDate ld = cal.to(LocalDate.class);
         System.out.println(cal.getTime() + " -> " + ld);
         LocalDateTime ldt = cal.to(LocalDateTime.class);
         System.out.println(cal.getTime() + " -> " + ldt);
         ZoneDateTime zdt = cal.to(ZoneDateTime.class);
         System.out.println(cal.getTime() + " -> " + zdt);

         Calendar jcal = Calendar.getInstance(Locale.forLanguageTag("ja-JP-u-ca-japanese"));
         @SuppressWarnings("unchecked")
         ChronoLocalDate<JapaneseChrono> jld
             = (ChronoLocalDate<JapaneseChrono>) jcal.to(JapaneseChrono.INSTANCE.dateNow().getClass());
         System.out.println(cal.getTime() + " -> " + jld);
         zdt = jcal.to(ZoneDateTime.class);
         System.out.println(cal.getTime() + " -> " + zdt);
     }
}

It's output:

Fri Dec 07 14:25:05 JST 2012 -> 2012-12-07
Fri Dec 07 14:25:05 JST 2012 -> 2012-12-07T05:25:05.285
Fri Dec 07 14:25:05 JST 2012 -> 2012-12-07T14:25:05.285+09:00[Asia/Tokyo]
Fri Dec 07 14:25:05 JST 2012 -> Japanese Heisei 24-12-07
Fri Dec 07 14:25:05 JST 2012 -> 2012-12-07T14:25:05.656+09:00[Asia/Tokyo]

It's not pretty, but works with the Japanese calendar.

LocalDateTime seems to ignore ZoneID in a DateTimeBuilder, but I guess 
it shouldn't.

Thanks,
Masayoshi



More information about the threeten-dev mailing list