Sunday, December 3, 2017

How to compare date with current time in JSTL

I am sharing some ways to solve the issue.

First:

I am going to presume it is a java.util.Date.
You can get the current date like this
<jsp:useBean id="now" class="java.util.Date"/>
You can then compare them using an EL expression:
{code}
<c:if test="${submitDate < now}">
We have not yet reached the submit date.
</c:if>{code}
EL uses the java compareTo methods, so both of your objects must be of the same class in order for this comparision to work.
If you get back a String from the database, you would have to use to get a java date. If you get back a java.sql.Date from the database, it would get trickier. The hack would be to go java.sql.Date -> String -> java.util.Date using <fmt:formatDate> and <fmt:parseDate>

Resource link:


Second:

<fmt:parseDate value="${found.submitDate}" pattern="yy/MM/dd" var="submitDate"/>
                                 <c:if test="${submitDate <now}">
                                     We have not yet reached the submit date.
                                 </c:if>

Third:

One clean way is to use the jsp:useBean tag to create a page-scoped variable containing the current date/time and then use normal JSTL to compare the objects.
First create the page-scoped java.util.Date object (using jsp:useBean), then use ${now} to reference the current date/time. This is a regular JSP object now and so the normal JSTL operators work with this variable:
<jsp:useBean id="now" class="java.util.Date"/>

<c:if test="${someEvent.startDate lt now}">
   It's history!
</c:if>

Resource Link:


Original Link: compare date with current time in jstl

No comments:

Post a Comment