Search code examples
spring-mvcthymeleaf

Number of days between two dates in Thymeleaf


How do you get the number of days between two dates in Thymeleaf?

Progress up until now:

<span th:text="${#dates.format(#dates.createNow(), 'dd/MMM/yyyy HH:mm') - #dates.format(feed.dateCreated, 'dd/MMM/yyyy HH:mm')}">Number of Days</span>

Any help would be highly appreciable. Thanks


Solution

  • As far as I know, this isn't something that Thymeleaf's utilities support, so it is kind of ugly to do. I tried this, and it works for me:

    <span th:with="days=${T(java.util.concurrent.TimeUnit).DAYS}, millis=${T(java.util.concurrent.TimeUnit).MILLISECONDS}" th:text="${days.convert(#dates.createNow().getTime() - feed.dateCreated.getTime(), millis)}" />
    

    Instead of doing all this in thymeleaf, I would probably add a getNumberOfDays() method to the feed object that returns the number of days and handle the diff in there. (Or use something like timeago.)