cancel
Showing results for 
Search instead for 
Did you mean: 

Freemarker date arithmetic

rhofkens
Champ in-the-making
Champ in-the-making
Hello,

I'm building a Freemarker Template that shows a grouped view of  the documents in a space:

- all docs changed today
- all docs changed yesterday
- all docs changed last week
- all docs changed last month

This would be easy enough to do using lucene queries with varying [date1] TO [date2] parts in the query.  Unfortunately, Freemarker doesn't seem to support date arithmetics, such as current_date - 1day and so on.

I don't like the idea of calculating the dates myself. Does anybody know of an easy way to do this in Freemarker?

Best regards,
3 REPLIES 3

kevinr
Star Contributor
Star Contributor
We have provided some custom methods to work on dates in FreeMarker - such as date compare and date increment:


* Usage:
*    dateCompare(dateA, dateB) - returns 1 if dateA if greater than dateB
*    dateCompare(dateA, dateB, millis) - returns 1 if dateA is greater than dateB by at least millis, else 0
(from the javadoc)

incrementDate(date, increment) - returns new date incremented by 'increment' milliseconds

Hope this helps,

Kevin

rhofkens
Champ in-the-making
Champ in-the-making
Hi Kevin,

great, the incrementDate function looks like the one I need.  I'll try out if this also works with a negative increment (effectively creating a decrementDate function).  If not, I'll implement decrementDate myself based on your code.

Cheers,
Roeland.

kevinr
Star Contributor
Star Contributor
The code looks like it simply converts the date to a long value, adds the increment long number value to the date (which can be a negative) and converts the resulting long back to a Date so it should work ok.

Thanks,

Kevin