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

问题描述

@H_502_0@我有以下JSP代码,并想为当前日期和第一列之间的月份差添加第二列。 $ {items}的列表在Controller中映射,该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>

@H_502_0@谢谢!

解决方法

假设firstDate的类型为LocalDate,则需要使用以下代码:

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

确保您import java.time.LocalDatejava.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切换到现代的日期时间和格式API。从 Trail: Date Time

了解有关现代日期时间API的更多信息