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.

Wednesday, April 9, 2014

Towers of Hanoi, Java implementation

Towers of Hanoi is a classic puzzle to move the discs of different sizes from one rod to another rod, in which the discs of larger sizes are never placed above the discs of smaller sizes.

The puzzle can be solved by a recursive or a non-recursive algorithms.

Recursive algorithm

The recursive algorithm is based on these actions:

Let the height of the origin peg be h,
1. Move h-1 discs from the origin peg to an open peg.
2. Move the h-th disc from the origin peg to the target peg.
3. Move the h-1 discs from the open peg to the target peg.

This algorithm reduces the problem from the peg(h) to the peg(h-1), peg(h-2) ....

The implementation is as follows: