获取jstl中的日期差异

Har*_*Joy 4 jstl date

我有一个日期,想显示与当前时间的差异--year--month--days--hours--minutes--seconds。我该怎么做jstl?确保该日期将大于当前日期时间。

Jos*_*ias 6

使用JSTL,您可以执行一些代码体操,例如:

<jsp:useBean id="now" class="java.util.Date" />
<fmt:parseNumber
    value="${(now.time - otherDate.time) / (1000*60*60*24) }"
    integerOnly="true" /> day(s) passed between given dates.
Run Code Online (Sandbox Code Playgroud)

但是,正如代码所暗示的那样,这给了整体差异,并且几乎不可能是“日历感知”的方式。即,您不能说:“ 自otherDate过去了3年零1个月零2天 ”。

使用JSP标记并使用“今天/昨天/过去的日子”演示文稿的这种“几天过去了...”样式的另一个示例:

<%--[...]--%>
<%@attribute name="otherDate" required="true" type="java.util.Date"%>

<jsp:useBean id="now" class="java.util.Date" scope="request"/>
<fmt:parseNumber
    value="${ now.time / (1000*60*60*24) }"
    integerOnly="true" var="nowDays" scope="request"/>

<fmt:parseNumber
    value="${ otherDate.time / (1000*60*60*24) }"
    integerOnly="true" var="otherDays" scope="page"/>

<c:set value="${nowDays - otherDays}" var="dateDiff"/>
<c:choose>
    <c:when test="${dateDiff eq 0}">today</c:when>
    <c:when test="${dateDiff eq 1}">yesterday</c:when>
    <c:otherwise>${dateDiff} day(s) ago</c:otherwise>
<%--[...]--%>
Run Code Online (Sandbox Code Playgroud)

注意:

在您的软件问题域中,如果有必要以日历的方式讨论几天和几个月,那么您应该在域模型中表达出来。如果没有,至少您应该受益于使用另一个较低的软件层来提供此信息(例如,使用java.util.Calendar或Joda-Time API)。


oll*_*_uk 0

不确定是否有任何内置方法可以使用 JSTL 执行此操作。您可以编写自己的标签库或可能使用如下所示的表达式语言(EL)。

${(dateObj) - (now.time)}
Run Code Online (Sandbox Code Playgroud)

取自寻找 JSTL Taglib 计算两个日期之间的秒数