---
description: JSP Date Handling All methods of core java can be used in JSP is the biggest advantage of JSP. In this section, we will be using Date class of java.util package, and it consists of date and time. It s
title: JSP Current Date and Time
image: https://www.guru99.com/images/jsp-current-date-time.png
---

 

[Skip to content](#main) 

**⚡ 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.

[ Read More ](javascript:void%280%29;) 

![JSP Current Date and Time](https://www.guru99.com/images/jsp-current-date-time.png) 

## JSP Date Handling

The biggest advantage of JSP is that all methods of core[ Java ](https://www.guru99.com/java-tutorial.html)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](https://www.guru99.com/jsp-tutorial.html) 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.

[](https://www.guru99.com/images/jsp/022916%5F0645%5FJSPActionFi22.png)

**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](https://www.guru99.com/jsp-action-tags.html).

<%@ 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.

### RELATED ARTICLES

* [JSP Tutorial ](https://www.guru99.com/jsp-tutorial.html "JSP Tutorial")
* [JSP Client Request ](https://www.guru99.com/jsp-client-request.html "JSP Client Request")
* [70 Spring Boot Interview Questions and Answers (2026) ](https://www.guru99.com/spring-boot-interview-questions.html "70 Spring Boot Interview Questions and Answers (2026)")
* [Top 40 Servlet Interview Questions and Answers (2026) ](https://www.guru99.com/servlet-interview-questions.html "Top 40 Servlet Interview Questions and Answers (2026)")

## 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

⚡ Which package must be imported to use Date in a JSP page?

`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.

🧠 How can AI assistants help with date handling code in JSP?

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.

🤖 Can GitHub Copilot generate JSP scriptlets for dates?

Yes. [GitHub Copilot](https://github.com/features/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.

🕒 Why does the page show the server time instead of the visitor time?

`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.

🧮 What is the difference between getTime() and toString()?

`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.

🔄 Is java.util.Date fully deprecated in modern Java?

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.

📝 Can a date be displayed without writing any Java in the page?

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.

🧩 Which expression tag prints a value straight into the HTML?

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:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/jsp-current-date-time.png","url":"https://www.guru99.com/images/jsp-current-date-time.png","width":"700","height":"250","caption":"JSP Current Date &amp; Time","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/jsp-date-handling.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/jsp","name":"JSP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/jsp-date-handling.html","name":"JSP Current Date and Time"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/jsp-date-handling.html#webpage","url":"https://www.guru99.com/jsp-date-handling.html","name":"JSP Current Date and Time","dateModified":"2026-07-29T17:09:24+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/jsp-current-date-time.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/jsp-date-handling.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"JSP","headline":"JSP Current Date and Time","description":"JSP Date Handling All methods of core java can be used in JSP is the biggest advantage of JSP. In this section, we will be using Date class of java.util package, and it consists of date and time. It s","keywords":"jsp","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-29T17:09:24+05:30","image":{"@id":"https://www.guru99.com/images/jsp-current-date-time.png"},"copyrightYear":"2026","name":"JSP Current Date and Time","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Which package must be imported to use Date in a JSP page?","acceptedAnswer":{"@type":"Answer","text":"java.util. Add &lt;%@ page import=\"java.util.*\" %&gt; 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."}},{"@type":"Question","name":"How can AI assistants help with date handling code in JSP?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can GitHub Copilot generate JSP scriptlets for dates?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Why does the page show the server time instead of the visitor time?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is the difference between getTime() and toString()?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Is java.util.Date fully deprecated in modern Java?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can a date be displayed without writing any Java in the page?","acceptedAnswer":{"@type":"Answer","text":"Yes. Declare the object with &lt;jsp:useBean&gt; and render it with the JSTL &lt;fmt:formatDate&gt; tag. No scriptlet is required, which keeps the markup readable and easier to maintain."}},{"@type":"Question","name":"Which expression tag prints a value straight into the HTML?","acceptedAnswer":{"@type":"Answer","text":"The expression tag &lt;%= %&gt;. 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."}}]}],"@id":"https://www.guru99.com/jsp-date-handling.html#schema-1154857","isPartOf":{"@id":"https://www.guru99.com/jsp-date-handling.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/jsp-date-handling.html#webpage"}}]}
```
