Servlet Handling Dates
One of the most important advantages of using Servlets is that most of the methods available in core Java can be used. This chapter explains the java.util in the package Date class provided by Java, which encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes an object with the current date and time.
Date( )
The second constructor accepts a parameter equal to the number of milliseconds elapsed since midnight on January 1, 1970.
Date(long millisec)
Once you have a Date object available, you can call any of the following supported methods to work with the date:
| No. | Method & Description |
|---|---|
| 1 | boolean after(Date date) |
| Returns true if the date contained in the calling Date object is after the date specified by date, otherwise returns false. | |
| 2 | boolean before(Date date) |
| Returns true if the date contained in the calling Date object is before the date specified by date, otherwise returns false. | |
| 3 | Object clone( ) |
| Duplicate the calling Date object. | |
| 4 | int compareTo(Date date) |
| Compares the value of the calling object with the value of date. Returns 0 if the two values are equal. Returns a negative value if the calling object is before date. Returns a positive value if the calling object is after date. | |
| 5 | int compareTo(Object obj) |
| If obj is of the Date class, the operation is equivalent to compareTo(Date). Otherwise, it throws a ClassCastException. | |
| 6 | boolean equals(Object date) |
| Returns true if the time and date contained in the calling Date object are the same as those specified by date, otherwise returns false. | |
| 7 | long getTime( ) |
| Returns the number of milliseconds elapsed since January 1, 1970. | |
| 8 | int hashCode( ) |
| Returns a hash code for the calling object. | |
| 9 | void setTime(long time) |
| Sets the time and date specified by time, which represents the time elapsed since midnight on January 1, 1970 (in milliseconds). | |
| 10 | String toString( ) |
| Converts the calling Date object to a string and returns the result. |
Getting the Current Date and Time
Getting the current date and time in a Java Servlet is very easy. You can use a simple Date object's toString() method to output the current date and time, as shown below:
package com.runoob.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CurrentDate
*/
@WebServlet("/CurrentDate")
public class CurrentDate extends HttpServlet {
private static final long serialVersionUID = 1L;
public CurrentDate() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Displaying the Current Date and Time";
Date date = new Date();
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"" + date.toString() + "
\n" +
"");
}
}
Now, let's compile the Servlet above and create the appropriate entries in the web.xml file:
CurrentDate
com.runoob.test.CurrentDate
CurrentDate
/TomcatTest/CurrentDate
Then invoke the Servlet by visiting http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:

Try refreshing the URL http://localhost:8080/TomcatTest/CurrentDate; every few seconds you will notice a difference in the displayed time.
Date Comparison
As mentioned above, you can use all available Java methods in a Servlet. If you need to compare two dates, here are the methods:
- You can use getTime() to obtain the time elapsed since midnight on January 1, 1970 for both objects (in milliseconds), and then compare the two values.
- You can use the methods before( ), after( ), and equals( ). Since the 12th of a month is before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
- You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Formatting Dates with SimpleDateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined pattern for date-time formatting.
Let's modify the example above as follows:
package com.runoob.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CurrentDate
*/
@WebServlet("/CurrentDate")
public class CurrentDate extends HttpServlet {
private static final long serialVersionUID = 1L;
public CurrentDate() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Displaying the Current Date and Time";
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss E a ");
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"" + ft.format(dNow) + "
\n" +
"");
}
}
Compile the Servlet above again, then invoke it by visiting http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:

Format Codes for Simple Date Formats
A pattern string is used to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as follows:
| Character | Description | Example |
|---|---|---|
| G | Era designator | AD |
| y | Year represented by four digits | 2001 |
| M | Month in a year | July or 07 |
| d | Day of the month | 10 |
| h | Hour with A.M./P.M. (1~12) | 12 |
| H | Hour of the day (0~23) | 22 |
| m | Minute in an hour | 30 |
| s | Second in a minute | 55 |
| S | Millisecond | 234 |
| E | Day of the week | Tuesday |
| D | Day of the year | 360 |
| F | Week of the month | 2 (second Wed. in July) |
| w | Week of the year | 40 |
| W | Week in a month | 1 |
| a | A.M./P.M. marker | PM |
| k | Hour of the day (1~24) | 24 |
| K | Hour with A.M./P.M. (0~11) | 10 |
| z | Timezone | Eastern Standard Time |
| ' | Escape for text | Delimiter |
| " | Single quote | ` |
For a complete list of available date-handling methods, you can refer to the standard Java documentation.