2

How can I do date manipulation in the Spring Expression language?

<si:service-activator id="entryReader" expression="@blogEntryReader.getEntriesBetweenDates(payload.startDate, payload.startDate **PLUS 30 DAYS**)" input-channel="blogEntryReaderChannel"/>
Adam
  • 43,763
  • 16
  • 104
  • 144

3 Answers3

3

Unfortunately, the java.util.Calendar doesn't have a builder API so it's not SpEL-friendly. One solution would be to use a helper class...

public static class CalendarManip {

    public static Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_YEAR, 30);
        return cal.getTime();
    }
}

Then, in SpEL...

T(foo.CalendarManip).addDays(payload.startDate, 30)

You could also use a <int-groovy:script/> if you don't want a helper class.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
1
T(org.apache.commons.lang.time.DateUtils).addDays(payload.startDate, 30)
  • Please explain your answer – Gwenc37 Jun 10 '14 at 13:45
  • A nice simple solution here... I would've thought it's fairly straightforward what's happening here...? Calling the static method addDays on the DateUtils class of apache commons – Samuel Parsonage Jun 25 '15 at 15:12
  • Neat solution, but unfortunately in newer version of Thymeleaf I get "Instantiation of new objects and access to static classes or parameters is forbidden in this context" – Bernie Lenz Apr 07 '23 at 17:30
0

If you have the access a tidier way to do this would be by writing the date manipulation functions you need and injecting them into the SpelEvaluationContext:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-ref-functions

NickV
  • 71
  • 3