JSP Current Date and Time

โšก Smart Summary

JSP date handling relies on plain core Java, so the java.util.Date class and its constructors can be called straight from a scriptlet or an expression tag to print the current date and time on a page.

  • ๐Ÿ”˜ Advantage: Every method of core Java remains available inside a JSP page without extra configuration.
  • โ˜‘๏ธ Constructors: Date() returns the current moment, while Date(long) rebuilds a moment from milliseconds since 1970.
  • โœ… Methods: after, before, compareTo, equals, getTime, setTime and toString cover most comparison work.
  • ๐Ÿงช Expression tag: A single expression tag prints the date object directly into the generated HTML.
  • ๐Ÿ› ๏ธ Formatting: SimpleDateFormat and the JSTL formatDate tag control exactly how the value appears.
  • ๐Ÿ“Š Modern API: java.time classes such as LocalDateTime replace the older Date methods marked deprecated.

JSP Current Date and Time

JSP Date Handling

The biggest advantage of JSP is that all methods of core Java can be used in JSP.

In this section, we will be using the Date class of the java.util package, which holds both a date and a time in a single object. The class is available on every JSP page as soon as the package is imported with a page directive.

It supports two constructors:

Constructor What it does
Date() It gives us the current date and time.
Date(long millisec) This takes a parameter of milliseconds which has elapsed since January 1, 1970.

The Date class also exposes the methods listed below. Java primitive return types are written in lower case, which is how they appear in the Java API.

Method Description
boolean after(Date date) It tells whether this date falls after the given date parameter.
boolean before(Date date) It tells whether this date falls before the given date parameter.
Object clone() It creates a copy of the date object.
int compareTo(Date date) It compares the date class object with another one.
int compareTo(Object date) It compares with the object class object with another one. This overload belongs to the pre-generics API; current Java exposes only compareTo(Date).
boolean equals(Object date) It checks whether two date objects are equal.
long getTime() It fetches the time as milliseconds since January 1, 1970.
int hashCode() It fetches the hash code of the given date.
void setTime(long time) It sets the time of the given date object.
String toString() It converts the date object into a string object.

Note: the field accessors of this class, such as getYear(), getMonth() and toLocaleString(), have been deprecated since JDK 1.1. The class itself still works, but new code is expected to use Calendar, DateFormat, or the java.time classes described further down this page.

Example: Display the Current Date and Time in JSP

Example:

In this example, we are fetching the current date and time using date object.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.*" %>
<!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>Guru current Date</title>
</head>
<body>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</body>
</html>

Explanation of the code:

Code Line 11: We are using date object to fetch the current date and time.

Modern equivalent: the code above is kept exactly as published. toLocaleString() was replaced by DateFormat.format(Date date) as of JDK 1.1, so a current page would write <%= java.text.DateFormat.getDateTimeInstance().format(new java.util.Date()) %> instead. The <%= %> expression tag itself is unchanged.

When you execute the above code, you get the following output.

Browser output of the JSP page printing the current date and time

Output:

We are getting current date and time.

How to Format Date and Time in JSP

Printing a Date object directly gives whatever the default locale produces, which is rarely the format a page needs. Two approaches control the output.

The first keeps the logic in Java and uses SimpleDateFormat, where each letter of the pattern stands for one part of the value.

<%@ page import="java.util.*, java.text.*" %>
<%
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String today = fmt.format(new Date());
%>
Today's date: <%= today %>
Pattern letter Meaning Example
yyyy Four-digit year 2026
MM Month number 07
dd Day of month 29
HH Hour, 24-hour clock 18
mm Minutes 45
ss Seconds 02

The second approach keeps the page free of Java code and uses the JSTL formatting library instead, which pairs well with the other JSP action tags.

<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<jsp:useBean id="now" class="java.util.Date" />
<fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss" />

The uri value shown above is the JSTL 3.0 form used by Jakarta EE 10 and later. Pages running on an older container still use http://java.sun.com/jsp/jstl/fmt, and containers keep accepting the older URI for compatibility. The type attribute selects date, time, or both, while dateStyle, timeStyle and timeZone refine the result.

Handling Dates with the java.time API in JSP

Java 8 introduced the java.time package, and it is now the recommended way to work with dates in any Java code, including a JSP page. Unlike Date, these classes are immutable and thread safe, so a single formatter can be shared safely across requests.

<%@ page import="java.time.*, java.time.format.*" %>
<%
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm");
%>
Today's date: <%= f.format(now) %>

Pick the class that matches what the page actually needs:

  • LocalDate โ€” a date with no time, such as a date of birth.
  • LocalTime โ€” a time with no date, such as an opening hour.
  • LocalDateTime โ€” a date and time with no time zone attached.
  • ZonedDateTime โ€” a date and time bound to a zone, for example ZoneId.of("Asia/Kolkata").
  • Instant โ€” a machine timestamp, the closest match to what getTime() returns.

Existing code does not have to be rewritten in one go, because Date.from(instant) and date.toInstant() convert between the two APIs.

Common Date Handling Errors in JSP

A date that prints correctly on a developer machine can still be wrong in production. The mistakes below account for most of those reports.

  • Missing import: using Date without <%@ page import="java.util.*" %> fails to compile unless the fully qualified java.util.Date is written out, as the example on this page does.
  • Wrong pattern letters: mm is minutes and MM is months, and DD is day of year rather than day of month.
  • Server time zone: new Date() reflects the clock of the server, not the visitor. Set timeZone on the formatting tag when the audience is elsewhere.
  • Sharing a SimpleDateFormat: the class is not thread safe, so a static instance shared across requests can return corrupted output. Create one per request, or use DateTimeFormatter.
  • Empty page after an upgrade: a container on Jakarta EE 10 rejects the old javax JSTL jars, so the formatting tag renders as literal text until the Jakarta artifacts are in place.
  • Formatting a string: a value pulled from a request parameter is text and must be parsed with parse() before any date method will accept it.

FAQs

java.util. Add <%@ page import="java.util.*" %> at the top of the page, or write the fully qualified java.util.Date inside the expression tag, which is what the example on this page does.

AI assistants can translate a format pattern into plain English, convert an older Date snippet into java.time, and point out a thread-safety problem in a shared formatter. Test the suggestion, because a wrong pattern letter still compiles cleanly.

Yes. GitHub Copilot completes scriptlets and taglib directives from a comment. Check the JSTL uri it produces, since it frequently defaults to the older java.sun.com value rather than the Jakarta one.

new Date() reads the clock and default zone of the server that runs the page. Pass an explicit zone to the formatter, or convert on the client, if the visitor’s local time is what matters.

getTime() returns a long: the milliseconds elapsed since 1 January 1970. toString() returns a readable string built from the default locale. Store the number, display the string.

No. The class remains supported, but most of its field accessors have carried a deprecation warning since JDK 1.1. New code is expected to use java.time, and Date.from() bridges the two APIs.

Yes. Declare the object with <jsp:useBean> and render it with the JSTL <fmt:formatDate> tag. No scriptlet is required, which keeps the markup readable and easier to maintain.

The expression tag <%= %>. Whatever it contains is evaluated and its toString() result is written into the response, which is how the sample page prints the date on a single line.

Summarize this post with: