[ Team LiB ] |
![]() ![]() |
Recipe 24.8 Formatting Dates in a JSPProblemYou want to display a date in a JSP that is customized for the user's locale. SolutionUse the fmt:formatDate JSTL tag. DiscussionThe 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>
The element has attributes named dateStyle and timeStyle that allow the code to customize the format of the date and time Strings.
The output of the JSP in Example 24-9 looks just like Figure 24-5 in the prior recipe. See AlsoThe Javadoc for the DateFormat class: http://java.sun.com/j2se/1.4.1/docs/api/java/text/DateFormat.html; Chapter 23 on the JSTL; Recipe 24.7 on formatting dates in a servlet. ![]() |
[ Team LiB ] |
![]() ![]() |