JSTL date comparisons with the current time (now) in JSPs

When you are coding JSPs and using the JSTL tags you will often be presenting information captured in a domain object, using the JavaBean-style getters to pull out the values within the JSP page.

What do you do if you need to show some text if the date stored within the domain object is before (or after) the current time?

There are many wrong or messy solutions - polluting the domain object by adding a method to 'get' the text to display, do the comparison in the controller and add the text to display to the request, etc.

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>
Technorati Tags: , , , , ,

11 comments:

Anonymous said...

Any idea how to take the difference of two dates, then output that as a date?

Anonymous said...

Thanks buddy. Its really helpful.

Anonymous said...

Good job..!!

Anonymous said...

Hi Andrew, is it possible to format the variable (now) to contain only YYYY-MM-DD? How can you do that?

Andy B said...

For formatting the date then you would need to use the formatDate tag from standard JSTL:



<fmt:formatDate pattern="yyyy-MM-dd" value="${now}" />

If you want the date variable itself to not have the time in it then one solution would be to use the DateMidnight class from the excellent JodaTime package.

Anonymous said...

Thank you so much. Easy to understand, and so easy to implement.

Pascual said...

Right now in Struts2 it's like this:

Pascual said...

Right now in Struts2 you get current date like this:

paone said...

Any idea how to take the difference of two dates, then output that as a no of days ?

paone said...

Any idea how to take the difference of two dates, then output that as a days?

paone said...

Any idea how to take the difference of two dates, then output that as a days?