1

I have the following JSP code and would like to add a second column for the difference in months between the current date and the first column. The List of ${items} is mapped in the Controller, which is calling the corresponding DAO method. Is there a way to do the calculation in the JSP file?

<table class="table">
<thead>
<tr>
<th>First Date</th>
<th>Months</th>
</tr>
</thead>

<tbody>
<c:forEach items="${items}" var="item">
<tr>
<td><fmt:formatDate value="${item.firstDate}" pattern="yyyy-MM-dd"/></td>
<td>"Here should be the difference in months between the current date and firstDate"</td>
</tr>
</c:forEach>
</tbody>
</table>

Thank you!

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
innoxius
  • 117
  • 2
  • 10

1 Answers1

1

Assuming the type of firstDate is LocalDate, you need to use the following code:

<td>${ChronoUnit.MONTHS.betwee(item.firstDate, LocalDate.now())}</td>

Make sure you import java.time.LocalDate and java.time.temporal.ChronoUnit.

The following program can be helpful to you in order to understand the code written above:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        System.out.println(ChronoUnit.MONTHS.between(LocalDate.parse("2019-08-10"), LocalDate.now()));
    }
}

Output:

12

By any chance, if the type of firstDate is java.util.Date, I suggest you switch from the error-prone legacy date-time and formatting API to the modern date-time and formatting API. Learn more about the modern date-time API from Trail: Date Time

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thank you Arvind! I forgot to specify that the SDK of the project is 1.7 and LocalDate and ChronoUnit are not available. – innoxius Aug 12 '20 at 15:11
  • 1
    @alexander java.time with `LocalDate` and `ChronoUnit` has been backported. Get [ThreeTen Backport](https://www.threeten.org/threetenbp/) and use the code from this answer with Java 1.7 too. – Ole V.V. Aug 12 '20 at 17:00