dinsdag 3 december 2013

Time for joda time

Introduction:


Calculating time in Java is doable but it is a bit of a pain in the backside. Using the calendar, getting the days and the hours and the minutes and calculate them one by one. I been playing around with joda time and that is a relieve. They encapsulated all the complex calcuations and retrieving in methods which can be chained when necesarry.

The example:

In this example I calculate the delivery date and time of a shop. It is calculating one of those days the shop has customized times. Like normally they start at 9 in the morning but this day they start at 8.

String opening = null;
opening = "8";
String[] defaultOpenTime = defaultTime.getDefaultOpeningTime().split(":");
int defaultOpenHour = Integer.parseInt(defaultOpenTime[0]);
int customizedOpenHour = Integer.parseInt(opening);
DateTime customTime = DateTime.parse("01-12-2013");
customTime =
                customTime.hourOfDay()
                .setCopy(customizedOpenHour)
                 .minuteOfHour()
                 .setCopy(opening);
 DateTime defaultTime =
                 DateTime.now()
                 .hourOfDay()
                 .setCopy(defaultOpenHour)
                  .minuteOfHour()
                  .setCopy(defaultOpenTime[1])
                  .secondOfMinute()
                  .setCopy(00);
Hours diffHours = Hours.hoursBetween(defaultTime,customTime);
delivery = delivery.plusHours(diffHours.getHours()  + MAX_DELIVER_TIME);
if(Integer.parseInt(opening) < delivery.getHourOfDay()){
//Normally I would retreive a value from a data store and add that here instead of the          
                          opening hours.
//In this case you can only help one customer after closing hours.
delivery = delivery.hourOfDay().setCopy(opening).minuteOfHour().setCopy(opening);
delivery = delivery.plusDays(NEXT_DAY);
}

There some points I like to highlight:

In this peace of code you create a DateTime object with the date and time you desire.
customTime =
                customTime.hourOfDay()
                .setCopy(customizedOpenHour)
                 .minuteOfHour()
                 .setCopy(opening);

In this peace of code you calculate hour difference:

Hours diffHours = Hours.hoursBetween(defaultTime,customTime);

You can do this also with days, minutes and seconds.

In this piece of code you jump to the next day:

delivery = delivery.plusDays(NEXT_DAY);

You can do this also with Hours, minutes and seconds.


Conclusion

Dealing with time is much easier when you do this with the joda-time library. There is also a Joda-money library I like to play with that the next time.


Have fun!