Search code examples
datejspjstlduration

How to calculate difference in months in JSP between date column and current date


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!


Solution

  • 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