Freemarker/Velocity - date manipulation

2019-04-02 14:46发布

问题:

I have a fairly simple question about these 2 templating engines.
I'm trying to make a future/past date, a fixed time from now, e.g. 18 months ago, or tomorrow.

I know that it is possible to do this with a java date object inside a velocity/freemarker template (something like $date.add(2,-18)), but I would like to do this with DateTool or freemarker core.

This is something that I see as purely presentational (just think at the default dates you see in flight booking forms), so I can't see any reason why a templating engine shouldn't be able to do this.

Is it possible though? If so, how?

回答1:

In Velocity Tools there is no such method.



回答2:

I know this is post is really old, but for people from the future still looking for an answer: Date manipulation can be done converting dates to/from milliseconds:

${(mydate?long - 18 * 86400000)?number_to_date?string("yyyy-MM-dd")}

for example would subtract 18 days from mydate. (Note that 86400000 is the amount of milliseconds per day)



回答3:

For freemarker, perhaps : Built-ins for dates.



回答4:

You can do it in Velocity too, but not with the DateTool (that belongs the Velocity Extras anyway).

It is a good practice to have a "Format" object with various utilities that are practical for presentational purposes only (you can see the various frameworks that use Velocity how they have "Format" objects).

So your code would look like $format.dateFromNow(), and there would be still a presentational approach.



回答5:

You can write your own methods to use in FreeMarker: http://freemarker.sourceforge.net/docs/pgui_datamodel_method.html

build a DataAddMethod that executes this logic.