小编典典

在jsp中显示日期差异

jsp

我在数据库中有一个日期字段,它只存储没有时间的日期。现在,我想知道在jsp页面中显示当前日期和我的日期字段中的天数差异。

所以我应该喜欢

 databaseDate(2012-11-30) - currentDate(2012-11-27)  = 3 days

阅读 263

收藏
2020-06-08

共1个答案

小编典典

标准JSTL中没有类似的东西。自定义EL功能将是您最好的选择。

首先实现一些执行该工作的静态方法:

public final class Functions {

    private Functions() {}

    public static int daysBetween(Date before, Date after) {
        // ...
    }

    public static int daysUntilToday(Date date) {
        // ...
    }

}

如果您在中进行如下注册/WEB-INF/functions.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>Custom_Functions</short-name>
    <uri>http://example.com/functions</uri>

    <function>
        <name>daysBetween</name>
        <function-class>com.example.Functions</function-class>
        <function-signature>boolean daysBetween(java.util.Date, java.util.Date)</function-signature>
    </function>
    <function>
        <name>daysUntilToday</name>
        <function-class>com.example.Functions</function-class>
        <function-signature>boolean daysUntilToday(java.util.Date)</function-signature>
    </function>
</taglib>

那么您将可以按以下方式使用它,只要它#{bean.date}返回一个完全有价值的代码即可java.util.Date

<%@taglib uri="http://example.com/functions" prefix="f" %>

${f:daysUntilToday(bean.date)} days

您可以自由选择实现。我个人更喜欢Joda Time

public static int daysBetween(Date before, Date after) {
    return Days.daysBetween(new DateTime(before.getTime()), new DateTime(after.getTime())).getDays();
}

public static int daysUntilToday(Date date) {
    return Days.daysBetween(new DateTime(date.getTime()), new DateTime()).getDays();
}

或者,如果您受限于标准Java API,请回到众所周知的Calendar样板文件(不幸的是,JSR-310并未将其纳入Java
7,我们必须等待
Java 8):

public static int daysBetween(Date before, Date after) {
    Calendar c1 = createCalendarWithoutTime(before);
    Calendar c2 = createCalendarWithoutTime(after);
    int days = 0;

    for (;c1.before(c2); days++) {
        c1.add(Calendar.DATE, 1);
    }

    return days;
}

public static int daysUntilToday(Date date) {
    return daysBetween(date, new Date());
}

private static Calendar createCalendarWithoutTime(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar;
}
2020-06-08