In JSTL, the <fmt:timeZone> tag is used to specify the time zone information for any date formatting in its body. This tag is different from <fmt:setTimeZone> in that, <fmt:setTimeZone> is used to set the default time zone. However, the <fmt:timeZone> tag sets the time zone for the tags within its body. Rest of the JSP page uses the time zone set by the <fmt:setTimeZone> or the default time zone.

 

JSTL <fmt:timeZone> Syntax:

<fmt:timeZone value="<string>"/>

 

Attributes:

Name

Required

Type

Description

    

value

True

java.lang.String

The required time zone value supported by the Java platform. We can give this value as America/New Yorkor as time zone code like GMT-8. Please see the class java.util.TimeZone for more information on supported time zones.

 

JSTL <fmt:timeZone> Example:

The following JSP code displays the current date using the default time zone and displays current date using the GMT-8 time zone. The GMT-8 time zone is set using the <fmt:timeZone> tag. Notice that we are displaying the date within the body of the <fmt:timeZone> tag.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>&lt;fmt:timeZone&gt; Demo</title>
  </head>
  <body>
    <h1>&lt;fmt:timeZone&gt; Demo</h1>
    <c:set var="today" value="<%=new java.util.Date()%>" />
    <c:set var="timeZone" value="GMT-8"/>
    Date in the current time zone:
    <strong><fmt:formatDate value="${today}" type="both" /></strong>
    <br/>
    Date in the GMT-8 time zone (nested in &lt;fmt:timeZone&gt; tag):
    <fmt:timeZone value="${timeZone}">
    <strong>
          <fmt:formatDate value="${today}" timeZone="${timeZone}" type="both" />
        </strong>
    </fmt:timeZone>
  </body>
</html>

 

Output:

timezone

 

Recommended Usage of <fmt:timeZone> tag:

The <fmt:timeZone>tag is particularly useful in scenarios where we only need to display date time which belongs to a different time zone at few places. In rest of the places, we may display date time using the default time zone.

 

Other JSTL Format Tags:

bundle  |  formatDate  |  formatNumber  |  message  |  param  |  parseDate  |  parseNumber  |  requestEncoding  |  setBundle  |  setLocale  |  setTimeZone


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment