Skip to main content

Java Date & Time manipulation using Apache Velocity

Apache Velocity is an excellent tool if you need to bang out a quick bit of XML output or a text file with a particular layout and you don't want to do it all in Java. You create a Velocity template with your text in it and use various place-holders for the dynamic data that will be passed into it from your Java code. Velocity them merges the two together to give you a nicely formatted custom-filled file/document/SOAP request/etc.

It's a great tool but does have it's quirks and downsides and one that I hit upon recently was how to display dates in a particular format. You can call methods on any Java object that you pass to the template but only if it's in the Java bean standard format of getX() and the Date formatting methods don't follow this standard.

The solution was found within the optional Velocity-Tools library - DateTool. DateTool has a number of format methods on it which can twist the dates and times into any format that you need, here are some examples:

Date & Time together

This in the template:
$dateTool.format('default', $testDate)
$dateTool.format('full', $testDate)
$dateTool.format('long', $testDate)
$dateTool.format('medium', $testDate)
$dateTool.format('short', $testDate)
Gives this in the output:
03-Jan-2012 00:00:00
Tuesday, 3 January 2012 00:00:00 o'clock GMT
03 January 2012 00:00:00 GMT
03-Jan-2012 00:00:00
03/01/12 00:00

Just Dates

This in the template:
$dateTool.format('default_date', $testDate)
$dateTool.format('full_date', $testDate)
$dateTool.format('long_date', $testDate)
$dateTool.format('medium_date', $testDate)
$dateTool.format('short_date', $testDate)
Gives this in the output:
03-Jan-2012
Tuesday, 3 January 2012
03 January 2012
03-Jan-2012
03/01/12

Just Times

This in the template:
$dateTool.format('default_time', $testDate)
$dateTool.format('full_time', $testDate)
$dateTool.format('long_time', $testDate)
$dateTool.format('medium_time', $testDate)
$dateTool.format('short_time', $testDate)
Gives this in the output:
00:00:00
00:00:00 o'clock GMT
00:00:00 GMT
00:00:00
00:00

Comments

Anonymous said…
Hi Andrew,

The date in my instance is in CST timezone
$date = March 5, 2017 6:26:27 PM CST

I am trying to change this date to GMT

Any suggestions?
Anonymous said…
Hi Andrew,

Date in my instance is
$date = March 5, 2017 6:26:27 PM CST

I am trying to change this date to GMT

any suggestions?