25 March 2010

Converting a String into a Calendar (using a pattern)

Valid since: op4j 1.0

Description
Create a java.util.Calendar object from a String, by applying a standard Java pattern to this String.

Scenario
Our date variable contains a String in the "dd/MM/yyyy" format, like:
String date = "06/12/1978";
...and we want to obtain a java.util.Calendar for this date.

Recipe
Operate on the String, and apply one of the FnString.toCalendar() variants (specifically, the one receiving a pattern).

Calendar cal =
    Op.on(date).exec(FnString.toCalendar("dd/MM/yyyy")).get();


Comments
This function creates truncated calendar objects, which means that all fields less significant than the least-significant of the specified fields are set to zero. In the example, the least-significant field in the pattern is day, and so hour, minute, second and millisecond are set to zero.

Let's compare with non-op4j normal Java code:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dDate = null;
try {
    dDate = dateFormat.parse(date);
} catch (ParseException e) {
    throw SomeException(e);
}
Calendar cal = Calendar.getInstance();
cal.setTime(dDate);

No comments:

Post a Comment