Monday, January 14, 2013

A new Date and Time API for Java 8

Why is a new Date and Time API needed for Java ?

This series of blogs is apart of the JoziJUG Adopt a JSR

Have a look at the following code as illustrated this document.
    Date date = new Date(2007, 12, 13, 16, 40);//Issue 1 and Issue 2
    TimeZone zone = TimeZone.getInstance("Asia/HongKong");//Issue 3
    Calendar cal = new GregorianCalendar(date, zone);//Issue 4
    DateFormat fm = new SimpleDateFormat("HH:mm Z");
    String str = fm.format(cal); //Issue 5

Issue 1 

The year should not be 2007, it should be 2007 - 1900. i.e. The year starts with 1900

Issue 2 

Months start with 0. So 0 is January , 11 is December and 12 is invalid.

Issue 3 

Asia/HongKong is a ISO standard timezone. But the API expects an underscore in the timezone name. e.g. Asia/Hong_Kong

Issue 4 

The constructor to GregorianCalendar or even method Calendar.getInstance(date) does not exist. A calendar needs to be created and then set.

Issue 5 

A SimpleDateFormat can not format a Calendar, the Calendar needs to be converted to a Date first

What about Joda Time ? 

Joda time is a widely used alternative to the standard Java Date and Time API but according to author it has flaws and can not just be included in the core Java.

In the next blog 

 I will discuss Joda time as we prepare to explore the already written JSR 310 code.

No comments:

Post a Comment