Servlet Date Handling
One of the most significant advantages of using Servlet is the ability to utilize most of the available methods in core Java. This chapter will explain the Date class from the java.util package 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 following constructor accepts a parameter that equals the number of milliseconds since midnight, January 1, 1970.
Date(long millisec)
Once you have a Date object available, you can call any of the following supported methods to manipulate the date:
No. | Method & Description |
---|---|
1 | boolean after(Date date) <br>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) <br>Returns true if the date contained in the calling Date object is before the date specified by date, otherwise returns false. |
3 | Object clone( ) <br>Duplicates the calling Date object. |
4 | int compareTo(Date date) <br>Compares the value of the calling object with that of date. Returns 0 if the 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) <br>Operates identically to compareTo(Date) if obj belongs to the Date class. Otherwise, it throws a ClassCastException. |
6 | boolean equals(Object date) <br>Returns true if the time and date of the calling Date object is the same as that specified by date, otherwise returns false. |
7 | long getTime( ) <br>Returns the number of milliseconds since January 1, 1970. |
8 | int hashCode( ) <br>Returns a hash code for the calling object. |
9 | void setTime(long time) <br>Sets the time and date as specified by time, which represents the time elapsed since midnight, January 1, 1970, in milliseconds. |
10 | String toString( ) <br>Converts the calling Date object into a string and returns the result. |
Getting Current Date and Time
Getting the current date and time in a Java Servlet is quite straightforward. You can use the toString() method of a simple Date object to output the current date and time, as shown below:
package com.tutorialpro.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 = "Display Current Date & Time";
```java
Date date = new Date();
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">" + date.toString() + "</h2>\n" +
"</body></html>");
}
}
Now, let's compile the above servlet and create the appropriate entry in the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>CurrentDate</servlet-name>
<servlet-class>com.tutorialpro.test.CurrentDate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CurrentDate</servlet-name>
<url-pattern>/TomcatTest/CurrentDate</url-pattern>
</servlet-mapping>
</web-app>
Then call the servlet by accessing http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:
Try refreshing the URL http://localhost:8080/TomcatTest/CurrentDate, and you will notice the difference in the time displayed every few seconds.
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 get the number of milliseconds since January 1, 1970, 00:00:00 GMT for both objects and then compare these two values.
You can use the methods before(), after(), and equals(). Since 12th of a month comes 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.
Using SimpleDateFormat to Format Dates
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Let's modify the above example as follows:
package com.tutorialpro.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 = "Display Current Date & Time";
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss E a ");
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">" + ft.format(dNow) + "</h2>\n" +
"</body></html>");
}
Recompile the above Servlet and then invoke the Servlet by accessing http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:
Simple Date Format Formatting Codes
Use an appropriate pattern string 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 indicator | AD |
y | Year in four digits | 2001 |
M | Month in year | July or 07 |
d | Day in month | 10 |
h | Hour in A.M./P.M. (1~12) | 12 |
H | Hour in day (0~23) | 22 |
m | Minute in hour | 30 |
s | Second in minute | 55 |
S | Millisecond | 234 |
E | Day in week | Tuesday |
D | Day in year | 360 |
F | Day of week in month | 2 (second Wed. in July) |
w | Week in year | 40 |
W | Week in month | 1 |
a | A.M./P.M. marker | PM |
k | Hour in day (1~24) | 24 |
K | Hour in A.M./P.M. (0~11) | 10 |
z | Time zone | Eastern Standard Time |
' | Escape for text | Delimiter |
" | Single quote | ` |
For a complete list of available date processing methods, you can refer to the standard Java documentation.