How to format date in JSP?

JSPJava 8Object Oriented ProgrammingProgramming

The <fmt:formatDate> tag is used to format dates in a variety of ways.

Attribute

The <fmt:formatDate> tag has the following attributes −

AttributeDescriptionRequiredDefault
ValueDate value to displayYesNone
typeDATE, TIME, or BOTHNodate
dateStyleFULL, LONG, MEDIUM, SHORT, or DEFAULTNodefault
timeStyleFULL, LONG, MEDIUM, SHORT, or DEFAULTNodefault
patternCustom formatting patternNoNone
timeZoneTime zone of the displayed dateNoDefault time zone
varName of the variable to store the formatted dateNoPrint to page
scopeScope of the variable to store the formatted dateNopage

The pattern attribute is used to specify even more precise handling of the date −

CodePurposeSample
GThe era designatorAD
yThe year2002
MThe monthApril & 04
dThe day of the month20
hThe hour(12-hour time)12
HThe hour(24-hour time)0
mThe minute45
sThe second52
SThe millisecond970
EThe day of the weekTuesday
DThe day of the year180
FThe day of the week in the month2 (2nd Wed in month)
wThe week in the year27
WThe week in the month2
aThe a.m./p.m. indicatorPM
kThe hour(12-hour time)24
KThe hour(24-hour time)0
zThe time zoneCentral Standard Time
'
The escape for text
''
The single quote

Example

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
   <head>
      <title>JSTL fmt:dateNumber Tag</title>
   </head>
   <body>
      <h3>Number Format:</h3>
      <c:set var = "now" value = "<% = new java.util.Date()%>" />
      <p>Formatted Date (1): <fmt:formatDate type = "time" value = "${now}" /></p>
      <p>Formatted Date (2): <fmt:formatDate type = "date" value = "${now}" /></p>
      <p>Formatted Date (3): <fmt:formatDate type = "both" value = "${now}" /></p>
      <p>Formatted Date (4): <fmt:formatDate type = "both" dateStyle = "short" timeStyle = "short" value = "${now}" /></p>
      <p>Formatted Date (5): <fmt:formatDate type = "both" dateStyle = "medium" timeStyle = "medium" value = "${now}" /></p>
      <p>Formatted Date (6): <fmt:formatDate type = "both" dateStyle = "long" timeStyle = "long" value = "${now}" /></p>
      <p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd" value = "${now}" /></p>
   </body>
</html>

The above code will generate the following result −

Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
raja
Published on 22-Mar-2019 15:12:38
Advertisements