小编典典

在JSP中使用Struts 2比较日期

jsp

我想使用比较两个日期 Struts2

One is returned from the backend  (test.currentDate) == "2012-11-15)"
The other one I just set "2014-10-19"

如何比较两个日期?

我的代码如下:

<s:set name="currentDate"  value="%{test.currentDate}"/>
<s:set name="futureDate" value="2014-10-19"/>
<s:if test="%{#currentDate.before(#futureDate)}">
    <s:text name="test"/> <s:date name="test.currentDate" format="MM/yy"/> 
</s:if>
<s:else>
    <s:text name="test2"/>
</s:else>

阅读 251

收藏
2020-06-08

共1个答案

小编典典

在上面,您试图将字符串与引起问题的日期对象进行比较。我建议您编写一个帮助程序类以比较日期并利用OGNL静态方法访问的优势。OGNLBasics-
访问静态属性

    <s:set var="currentDate" value="%{new java.util.Date()}"/>
    <s:set var="futureDate" value="%{new java.util.Date()}"/>
    <s:property value="{#currentDate}"/>
    <s:property value="{#futureDate}"/>
    <s:if test="%{@com.mycompany.temp.strtus2.example.HelloWorld@compareDate(#currentDate, #futureDate)}">
        <div>Do your stuff</div>
    </s:if>
    <s:else>
        <div>else condition</div>
    </s:else>

实用类

public static boolean compareDate(Date currentDate, Date futureDate) {
    boolean flag = false;
    if (removeTime(currentDate).equals(removeTime(futureDate))) {
        flag = true;
    } 
    return flag;
}

public static Date removeTime(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}
2020-06-08