I have a date field in database which store just date without time. Now I want to know the number of days difference in current date and my date field while displaying that
There's nothing like that in standard JSTL. A custom EL function would be your best bet.
First implement some static methods which performs the job:
public final class Functions {
private Functions() {}
public static int daysBetween(Date before, Date after) {
// ...
}
public static int daysUntilToday(Date date) {
// ...
}
}
If you register it as follows in /WEB-INF/functions.tld
:
1.0
Custom_Functions
http://example.com/functions
daysBetween
com.example.Functions
boolean daysBetween(java.util.Date, java.util.Date)
daysUntilToday
com.example.Functions
boolean daysUntilToday(java.util.Date)
then you'll be able to use it as follows, provided that #{bean.date}
returns a fullworthy java.util.Date
:
<%@taglib uri="http://example.com/functions" prefix="f" %>
${f:daysUntilToday(bean.date)} days
The implementation is free to your choice. I'd personally prefer 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();
}
Or if you're restricted to standard Java API, fall back to the well known Calendar
boilerplate (unfortunately, JSR-310 didn't made it into Java 7, we've to wait for 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;
}