Skip to main content


Showing posts from March, 2012

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: