Monday, June 9, 2014

Joda-Time Library, the tools help to compare datetime's with time zones

Riddle you this: Given a table of records with different date and time. You have a requirement to retrieve the earliest record that meets a specific date and time. The given time may be attached with a timezone. How would you implement this in Java?

Java does provide a package in java.util.date. Unfortunately, the package is timezone independent. In additions, adding or subtracting a date by an amount of a month/day/year may not be an easy task too. 

Here comes the Joda-Time library that can resolve your problem. There are several advantages using Joda-Time: 

  • Joda-Time supports the ISO 8601 standard. A datetime specified in the ISO 8601 standard is represented as this: YYYY-MM-DDThh:mm:ss±hh:mm. This gives a universal representation of date-time. 
  • Better Parsing Rules - Joda-Time parses a date-time better than a SimpleDateFormatter. A date like "2014-02-31" is considered an error in Joda-Time, while a SimpleDateFormatter conversion may return a date as "2014-03-03". 

Following is an example. The input parameter of a constructor is an ISO 8601 standardized date string. 

import org.joda.time.DateTime;

public class DateRequest {

       private final DateTime asofdate;

       public DateRequest(String dateInput) {
              this.date = new DateTime(dateInput);
       }
      
       public boolean meet(Date date) {

              return date.isAfter(new DateTime(date));
       }
}

Remember, the constructor of a Joda-Time date-time class accepts a NULL value, which returns an object with the current date-time of a timezone that specified from a machine. As your request may have come from different parts of the world, the use of a NULL value constructor may lead to some unwanted results.

For more details, you may go to Joda-Time website.