Freemarker/Velocity - date manipulation

2019-04-02 14:47发布

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?

5条回答
放荡不羁爱自由
2楼-- · 2019-04-02 15:28

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楼-- · 2019-04-02 15:29

For freemarker, perhaps : Built-ins for dates.

查看更多
不美不萌又怎样
4楼-- · 2019-04-02 15:37

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.

查看更多
爷的心禁止访问
5楼-- · 2019-04-02 15:40

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.

查看更多
霸刀☆藐视天下
6楼-- · 2019-04-02 15:45

In Velocity Tools there is no such method.

查看更多
登录 后发表回答