Monday, 9 January 2012

Know your date format

When it comes to date formatting, java makes use of SimpleDateFormat class:

"Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing."

When it comes to Jackrabbit internal, dates as saved to a specific format like the following string:
 2012-01-04T23:59:59.999+02:00
Taking forward to create the pattern for such a String results in:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
Note that we need T not to be a pattern letter, so we unquoted it. We may think everything it's ok. If we need just to show a nice formatted date, we may not even see the difference. But if we want to use date formatted strings for some business, for example to do a Jackrabbit search of entities between two dates, we will found out (not easily) that the pattern is wrong.

Jackrabbit has a xs:dateTime function which has a formatted date as parameter. Obviously this date must have the same format used to store dates in Jackrabbit.

The problem with previously date format is the time zone, because there is no delimiter between the hours and the minutes, so the resulting string with SimpleDateFormat will be :
2012-01-04T23:59:59.999+0200
Because we cannot use a SimpleDateFormat string, we must use Jackrabbit api to format dates:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formattedDate = ValueFactoryImpl.getInstance().createValue(cal).getString();

No comments:

Post a comment