I have a maven archetype project. When I use this archetype I want that some files report the actual date. I tried with $date but Velocity does not recognize it. I found something called DateTools but I don't know how can I use it. It's the first time I use Velocity.
问题:
回答1:
Unfortunately, the Maven Archetype plugin doesn't come bundled with Velocity Tools. I've added it by modifying the Maven Archetypes Plugin. Follow these steps, presuming you're using Maven 2.2.1:
svn co -q http://svn.apache.org/repos/asf/maven/archetype/tags/maven-archetype-2.2
cd maven-archetype-2.2
curl -k -O https://raw.github.com/gist/3404715/59c7fa1c20c60e2a165de4109c2acffb8026febd/velocity-tools.patch
patch -p0 -i velocity-tools.patch
mvn install
The modified Maven Archetype plugin will now be installed locally.
$date
usage in your templates should now render, e.g.
The date is $date
...to:
The date is Aug 20, 2012 4:40:22 PM
回答2:
(Apologies for resurrecting an old question, but I have just worked through a way to achieve this without the need to pull and patch the plugin).
For anyone that wants to be able to reference date fields in their maven archetype templates, I was able to get it working with the following set of definitions at the top of my pom.xml template
#set( $str = "" )
#set( $dt = $str.getClass().forName("java.util.Date").newInstance() )
#set( $year = $dt.getYear() + 1900 )
If you already have object based variables available to your template at the point that you insert those lines, you can scratch the $str declaration and use one of your variables instead as it doesn't really matter where you get the reference to Class.forName() from.
NOTE: My attempts to get this working with Calendar.getInstance() were unsuccessful.
回答3:
I managed to trim down the solution from @maaxiim to a single line:
#set( $year = $package.getClass().forName("java.util.Date").newInstance().getYear() + 1900 )
The $package variable will always be available from the maven archetype plugin. The other builtins work as well, but most of them are quite long, and $artifactId.getClass() just looks... wrong.
回答4:
In Java 8, with a formatter:
#set( $ldt = $package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null) )
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass()).invoke(null, "yyyy/MM/dd HH:mm:ss") )
#set( $date = $ldt.format($dtf) )