YouTip LogoYouTip

Servlet Handling Date

Servlet Handling Dates \n\n

One of the most important advantages of using Servlets is the ability to use most of the available methods in core Java. This chapter will explain the Date class provided in the java.util package by Java, which encapsulates the current date and time.

\n\n

The Date class supports two constructors. The first constructor initializes an object with the current date and time.

\n\n

Date( )

\n\n

The following constructor accepts a parameter that equals the number of milliseconds elapsed since midnight, January 1, 1970.

\n\n

Date(long millisec)

\n\n

Once you have a Date object available, you can call any of the following supported methods to use the date:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
IndexMethod & Description
1boolean after(Date date) Returns true if the date contained in the calling Date object is after the date specified by date; otherwise, returns false.
2boolean before(Date date) Returns true if the date contained in the calling Date object is before the date specified by date; otherwise, returns false.
3Object clone( ) Duplicates the calling Date object.
4int compareTo(Date date) 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 earlier than date. Returns a positive value if the calling object is later than date.
5int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
6boolean equals(Object date) Returns true if the time and date represented by the calling Date object and date are equal; otherwise, returns false.
7long getTime( ) Returns the number of milliseconds elapsed since January 1, 1970.
8int hashCode( ) Returns a hash code for the calling object.
9void setTime(long time) Sets the time and date as specified by time, which represents the number of milliseconds elapsed since midnight, January 1, 1970.
10String toString( ) Converts the calling Date object into a string and returns the result.
\n\n

It is very easy to get the current date and time in a Java Servlet. You can use a simple Date object's toString() method to output the current date and time, as shown below:

\n\n
package com.tutorial.test;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Servlet implementation class CurrentDate\n */\n@WebServlet("/CurrentDate")\npublic class CurrentDate extends HttpServlet {\n    private static final long serialVersionUID = 1L;\n\n    public CurrentDate() {\n        super();\n    }\n\n    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n        response.setContentType("text/html;charset=UTF-8");\n        PrintWriter out = response.getWriter();\n\n        String title = "Displaying Current Date and Time";\n        Date date = new Date();\n        String docType = "<!DOCTYPE html> n";\n\n        out.println(docType + "<html>n" +\n            "<head><title>" + title + "</title></head>n" +\n            "<body bgcolor="#f0f0f0">n" +\n            "<h1 align="center">" + title + "</h1>n" +\n            "<h2 align="center">" + date.toString() + "</h2>n" +\n            "</body></html>");\n    }\n}\n
\n\n

Now, let us compile the above Servlet and create an appropriate entry in the web.xml file:

\n\n
<?xml version="1.0" encoding="UTF-8"?>\n<web-app>\n\n  <servlet>\n    <servlet-name>CurrentDate</servlet-name>\n    <servlet-class>com.tutorial.test.CurrentDate</servlet-class>\n  </servlet>\n\n  <servlet-mapping>\n    <servlet-name>CurrentDate</servlet-name>\n    <url-pattern>/TomcatTest/CurrentDate</url-pattern>\n  </servlet-mapping>\n\n</web-app>\n
\n\n

Now call this Servlet using the URL http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:

\n\n

Image 1

\n\n

Try refreshing the URL http://localhost:8080/TomcatTest/CurrentDate every few seconds, and you will notice a difference in the displayed time.

\n\n

As mentioned above, you can use all available Java methods in a Servlet. If you need to compare two dates, here are the methods:

\n\n
    \n
  • You can use getTime() to get the number of milliseconds elapsed since midnight, January 1, 1970, for both objects, and then compare these two values.
  • \n
  • You can use the methods before(), after(), and equals(). Since the 12th of a month comes before the 18th, for example, new Date(99, 2, 12).before(new Date(99, 2, 18)) returns true.
  • \n
  • You can use the compareTo() method, which is defined by the Comparable interface and implemented by Date.
  • \n
\n\n

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date-time formatting pattern.

\n\n

Let us modify the above example as follows:

\n\n
package com.tutorial.test;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Servlet implementation class CurrentDate\n */\n@WebServlet("/CurrentDate")\npublic class CurrentDate extends HttpServlet {\n    private static final long serialVersionUID = 1L;\n\n    public CurrentDate() {\n        super();\n    }\n\n    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n        response.setContentType("text/html;charset=UTF-8");\n        PrintWriter out = response.getWriter();\n\n        String title = "Displaying Current Date and Time";\n        Date dNow = new Date( );\n        SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss E a ");\n        String docType = "<!DOCTYPE html> n";\n\n        out.println(docType + "<html>n" +\n            "<head><title>" + title + "</title></head>n" +\n            "<body bgcolor="#f0f0f0">n" +\n            "<h1 align="center">" + title + "</h1>n" +\n            "<h2 align="center">" + ft.format(dNow) + "</h2>n" +\n            "</body></html>");\n    }\n}\n
\n\n

Compile the above Servlet again and call it using the URL http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:

\n\n

Image 2

\n\n

Use event pattern strings to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as follows:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CharacterDescriptionInstance
GEra IndicatorAD
yFour-digit year2001
MMonth of the yearJuly or 07
dDay of the month10
hWith A.M./P.M. Hour (1-based)~12οΌ‰12
HHour of the day (0-based)~23οΌ‰22
mMinute of the hour30
sSecond of the minute55
SMillisecond234
EDay of the weekTuesday
DDay of the year360
FWeek of the month2 (second Wed. in July)
wWeek of the year40
WWeek of the month1
aA.M./P.M. FlagPM
kHour of the day (1-based)~24οΌ‰24
KWith A.M./P.M. Hour (0-based)~11οΌ‰10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote`
\n\n

For a complete list of available date-handling methods, you can refer to the standard Java documentation.

← Servlet Page RedirectServlet File Uploading β†’