Servlet Handling Dates

One of the most important advantages of using Servlets is that you can use most of the available methods in core Java. This chapter will explain the Java-providedjava.utilpackage'sDateclass, 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 elapsed since midnight, January 1, 1970.

Date(long millisec)

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

Serial numberMethod & Description
1boolean after(Date date)
Returns true if the date contained in the invoked Date object is after the date specified by date, otherwise returns false.
2boolean before(Date date)
Returns true if the date contained in the invoked Date object is before the date specified by date, otherwise returns false.
3Object clone( )
Duplicates the invoking Date object.
4int compareTo(Date date)
Compares the value of the invoking object with the value of date. Returns 0 if the two values are equal. Returns a negative value if the invoking object is before date. Returns a positive value if the invoking object is after date.
5int compareTo(Object obj)
If obj is of the Date class, the operation is equivalent to compareTo(Date). Otherwise, it throws a ClassCastException.
6boolean equals(Object date)
Returns true if the time and date contained in the invoked Date object are the same as those specified by date, otherwise returns false.
7long getTime( )
Returns the number of milliseconds elapsed since January 1, 1970.
8int hashCode( )
Returns a hash code for the invoking object.
9void setTime(long time)
Sets the time and date specified by time, which represents the time elapsed since midnight, January 1, 1970 (in milliseconds).
10String toString( )
Converts the invoking Date object to a string and returns the result.

Get 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'stoString()method to output the current date and time, as shown below:

package com.example.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 = "显示当前的日期和时间";
        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.example.test.CurrentDate</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CurrentDate</servlet-name>
    <url-pattern>/TomcatTest/CurrentDate</url-pattern>
  </servlet-mapping>
</web-app>

Then invoke the Servlet by accessing http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:

Try refreshing the URL http://localhost:8080/TomcatTest/CurrentDate. Every time you refresh after a 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, January 1, 1970 (in milliseconds) for both objects, and then compare these two values.
  • You can use the methods before(), after(), and equals(). Since the 12th comes before the 18th in a month, 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.

Use SimpleDateFormat to format dates

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.

Let's modify the above example as follows:

package com.example.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 = "显示当前的日期和时间";
        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>");
    }

}

Compile the above Servlet again, then invoke it by accessing http://localhost:8080/TomcatTest/CurrentDate. This will produce the following result:


Simple date format format codes

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

CharacterDescriptionExample
GEra indicatorAD
yYear represented by four digits2001
MMonth in the yearJuly or 07
dDay in the month10
hHour with A.M./P.M. (1-12)12
HHour in the day (0-23)22
mMinute in the hour30
sSecond in the minute55
SMillisecond234
EDay of the weekTuesday
DDay of the year360
FWeek of the month2 (second Wed. in July)
wWeek of the year40
WWeek in the month1
aA.M./P.M. markerPM
kHour in the day (1-24)24
KHour with A.M./P.M. (0-11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote`

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

Other extensions