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
First create the page-scoped
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"/>Technorati Tags: Java, JSP, JSTL, Date, Comparison, Andrew Beacock
<c:if test="${someEvent.startDate lt now}">
It's history!
</c:if>
Comments
<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.