O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

24.8. Formatting Dates in a JSP

Problem

You want to display a date in a JSP that is customized for the user's locale.

Solution

Use the fmt:formatDate JSTL tag.

Discussion

The JSTL includes the "formatting" library, which allows JSP code to display dates in a locale-sensitive manner. Example 24-9 uses the fmt:formatDate tag. The code uses the standard action jsp:useBean to create a java.util.Date object representing the current date and time. The code passes the date object to fmt:formatDate's value attribute. When a user requests the JSP, the fmt:formatDate tag is replaced by text displaying the formatted date.

Example 24-9. Formatting a date using fmt:formatDate

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<jsp:useBean id="date" class="java.util.Date" />

<html>
<head><title> <fmt:message key="Welcome" /> </title></head>
<body>

<h2> <fmt:message key="Hello" /> <fmt:message key="and" /> 
  <fmt:message key="Welcome" /> </h2>

<fmt:formatDate value="${date}" type="both" dateStyle=
  "full" timeStyle="short" /> <br />

Locale: <c:out value=
  "${pageContext.request.locale.language}" />_<c:out value=
   "${pageContext.request.locale.country}" /> 

</body>
</html>

Tip

The fmt:message tags here depend on a configuration parameter, or context-param element, in the deployment descriptor. The context-param element specifies the i18n-related resources . See Recipe 24.13.

The element has attributes named dateStyle and timeStyle

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required