English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Date Handling

One of the most important advantages of using Servlets is that most of the available methods in core Java can be used. This chapter will explain the methods provided by Java. java.util in the Date class, 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 equal to 197You can use getTime() to get the time elapsed since 1 0 years 1 milliseconds elapsed since midnight of the day.

Date(long millisec)

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

Serial NumberMethod & Description
1boolean after(Date date)
return true if the date contained in the called Date object is after the specified date, otherwise return false.
2boolean before(Date date)
return true if the date contained in the called Date object is before the specified date, otherwise return false.
3Object clone( )
repeated calls to the Date object.
4int compareTo(Date date)
compare the value of the called object with the value of date. If the two values are equal, return 0. If the called object is before date, return a negative value. If the called object is after date, return a positive value.
5int compareTo(Object obj)
if obj is a Date class, the operation is equivalent to compareTo(Date). Otherwise, it will throw a ClassCastException.
6boolean equals(Object date)
return true if the date and time contained in the called Date object are the same as those specified by date, otherwise return false.
7long getTime( )
return 197You can use getTime() to get the time elapsed since 1 0 years 1 milliseconds elapsed since the specified date.
8int hashCode( )
return the hash code for the called object.
9void setTime(long time)
set time to the specified date and time, which means from 197You can use getTime() to get the time elapsed since 1 0 years 1 time elapsed since midnight of the day (in milliseconds).
10String toString( )
convert the called Date object to a string and return the result.

to get the current date and time

It is very easy to get the current date and time in Java Servlet. You can use a simple Date object's toString() toString()}

package com.w;3codebox.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();
    html>
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8-8
        PrintWriter out = response.getWriter();
          String title = "Display the current date and time";
        Methods to output the current date and time as follows:
        String docType = "<!DOCTYPE html> \n";
          out.println(docType +
            "<html>\n" +
            "<head><title>" + title + /title></head>\n" +
            "<body bgcolor="#f0f0f0">\n" +
            "<h1 align="center">" + title + /Day of the month1 +
            "<h2 align="center">" + Date date = new Date(); + /Day of the month2 +
            /"</body><
    html>
html>

date.toString()

Now, let's compile the above Servlet and create the appropriate entry in the web.xml file:1<?xml version="-8.0" encoding="UTF
"?>-web
  <web
    servlet>-<servlet/pattern>-name>CurrentDate<
    servlet>-<servlet>3class>com.w/pattern>-codebox.test.CurrentDate<
  mapping>/class>
  servlet>-servlet
    servlet>-<servlet/pattern>-name>CurrentDate<
    name>-url/localhost:/<url/CurrentDate<-url
  mapping>/pattern>-servlet
mapping>/<-web

app>//Recompile the above Servlet and then access http:8080/localhost:/TomcatTest

Then access http://Recompile the above Servlet and then access http:8080/localhost:/Try to refresh the URL http:

CurrentDate, every few seconds you refresh, you will find the difference in the displayed time.

Date comparison

  • As mentioned above, you can use all available Java methods in Servlets. If you need to compare two dates, here is the method: 197You can use getTime() to get the time elapsed since 1 0 years 1 Month

  • You can use the methods before(), after(), and equals(). Since the time passed since midnight of the day in a month (in milliseconds), then compare these two values. 12 The number is 18 Before the number, 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 using SimpleDateFormat

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

Let us modify the above example as follows:

package com.w;3codebox.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();
    html>
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8-8
        
        PrintWriter out = response.getWriter();
        String title = "Display the current date and 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 + /Day of the month1 +
            "<h2 align="center">" + ft.format(dNow) + /Day of the month2 +
            /"</body><
    html>
html>

}//Recompile the above Servlet and then access http:8080/localhost:/TomcatTest

To call this Servlet, use CurrentDate. This will produce the following result:

Simple date format format codes

Use the event pattern string to specify the date format. In this mode, all ASCII letters are preserved as pattern letters, which are defined as follows:CharacterDescription
ExampleGEra Indicator
A.D.y2Year represented by four digits1
00MMonth of the year7
July or 0d10
Day of the monthK/h1Which hour of the day (12P.M. Hour (0~12
P.M. Hour (H23P.M. Hour (0~22
Hour of the day (0~m30
Minute of the hours55
Second of the minuteS234
MillisecondEDay of the week
TuesdayD360
Day of the yearF2 The week of the month
w(second Wed. in July)40
Week of the yearW1
Week of the montha/A.M.P.M. Indicator
P.M.k1Which hour of the day (24P.M. Hour (0~24
~K/With A.M.11P.M. Hour (0~10
)zTime Zone
Eastern Standard Time'Escape for text
DelimiterSingle Quote`

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