Friday, July 28, 2006

Get the Current Date/Time in JSTL

Get the current date like so:
<jsp:useBean id="now" class="java.util.Date" />

Or you can parse a string date into a date object
<fmt:parseDate var="mydate" pattern="yyyy-MM-dd">${stringHoldingDate}</fmt:parseDate>

Now format it as you like (calling formatDate will return the formatted date as a string, place the code inside a <c:set></c:set> to set as a variable; otherwise, it will print out to the screen):
<fmt:formatDate value="${now}" type="both" pattern="MM/dd/yyyy HH:mm:ss" />


You must use type=both otherwise the time will not be parsed, even if the format contains it!

1 comment:

Allen said...

Excellent, that worked. I was using some old code, so I had to add /jsp to the include to avoid an "attribute does not accept any expressions" error.

Full include:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

Labels

Blog Archive

Contributors