Recipe 24.8 Formatting Dates in a JSP


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


Use the fmt:formatDate JSTL tag.


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="" prefix="c" %> <%@ taglib uri="" 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=    "${}" />  </body> </html> 

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 that allow the code to customize the format of the date and time Strings .

See the Javadoc for the DateFormat class for more details:

The output of the JSP in Example 24-9 looks just like Figure 24-5 in the prior recipe.

See Also

The Javadoc for the DateFormat class:; Chapter 23 on the JSTL; Recipe 24.7 on formatting dates in a servlet.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: