如何计算日期列和当前日期之间 JSP 中的月份差异

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

我有以下 JSP 代码,并想为当前日期和第一列之间的月份差异添加第二列。 ${items} 的List 映射到Controller 中,调用相应的DAO 方法。有没有办法在 JSP 文件中进行计算?

<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>

谢谢!

假设firstDate的类型是LocalDate,需要使用如下代码:

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

确保你 import java.time.LocalDate and java.time.temporal.ChronoUnit.

下面的程序可以帮助你理解上面写的代码:

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()));
    }
}

输出:

12

万一,如果firstDate的类型是java.util.Date,我建议你从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

切换