09 April 2010

Creating a Calendar from day, month and year

Valid since: op4j 1.0

Create a java.util.Calendar object containing a specific date from its components (day, month and year) in a simple way.

We want to create a variable called date, of type java.util.Calendar, containing the following date:
// date == CALENDAR: 12 October, 1492. 00:00:00:000

The FnCalendar function hub class from op4j provides us with a useful fieldIntegerListToCalendar() function, which we could use for solving our scenario in a very elegant way, just creating a list with the date components (year, month, day), and then applying the function:

Calendar date = 
    Op.onListFor(1492, 10, 12).exec(FnCalendar.fieldIntegerListToCalendar()).get();

Let's see the equivalent non-op4j Java code for this:
Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_MONTH, 12);
date.set(Calendar.MONTH, Calendar.OCTOBER);
date.set(Calendar.YEAR, 1492);

And... what if we wanted to be more specific and set the hour and minutes like:
// date == CALENDAR: 12 October, 1492. 02:34:00:000
Calendar date = 
    Op.onListFor(1492, 10, 12, 2, 34).exec(FnCalendar.fieldIntegerListToCalendar()).get();

No comments:

Post a Comment