Latest web development tutorials

Servlet Date Processing

One of the most important advantages of using Servlet that can be used in most of the core Java methods available. This chapter will explainthe java.util package provided by the Java Dateclass that encapsulates the current date and time.

Date class supports two constructors. The first constructor to initialize the object the current date and time.

Date( )

The following constructor accepts a parameter that is equal to the number of milliseconds elapsed since January 1, 1970 at midnight.

Date(long millisec)

Once you have an available Date object, you can call any of the following ways to use support Date:

序号方法 & 描述
1boolean after(Date date)
如果调用的 Date 对象中包含的日期在 date 指定的日期之后,则返回 true,否则返回 false。
2boolean before(Date date)
如果调用的 Date 对象中包含的日期在 date 指定的日期之前,则返回 true,否则返回 false。
3Object clone( )
重复调用 Date 对象。
4int compareTo(Date date)
把调用对象的值与 date 的值进行比较。如果两个值是相等的,则返回 0。如果调用对象在 date 之前,则返回一个负值。如果调用对象在 date 之后,则返回一个正值。
5int compareTo(Object obj)
如果 obj 是 Date 类,则操作等同于 compareTo(Date)。否则,它会抛出一个 ClassCastException。
6boolean equals(Object date)
如果调用的 Date 对象中包含的时间和日期与 date 指定的相同,则返回 true,否则返回 false。
7long getTime( )
返回 1970 年 1 月 1 日以来经过的毫秒数。
8int hashCode( )
为调用对象返回哈希代码。
9void setTime(long time)
设置 time 指定的时间和日期,这表示从 1970 年 1 月 1 日午夜以来经过的时间(以毫秒为单位)。
10String toString( )
转换调用的 Date 对象为一个字符串,并返回结果。

Gets the current date and time

Gets the current date and time in the Java Servlet is very easy. You can use a single Date object'stoString ()method to output the current date and time as follows:

package com.w3big.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.w3big.test.CurrentDate</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CurrentDate</servlet-name>
    <url-pattern>/TomcatTest/CurrentDate</url-pattern>
  </servlet-mapping>
</web-app>

Then visit http: to call the Servlet 8080 / TomcatTest / CurrentDate: // localhost. This will produce the following results:

Try to refresh the URL http: // localhost: 8080 / TomcatTest / CurrentDate, refresh every few seconds difference you'll find a display time.

Compare dates

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

  • You can use the getTime () to get the two objects, since January 1, 1970 midnight elapsed time (in milliseconds), then these two values.
  • You can use the method before (), after () and equals (). Since the 12th until the 18th, for example, new Date (99, 2, 12) .before (new Date (99, 2, 18)) returns the month true.
  • You can use the compareTo () method, which is defined by the Comparable interface by Date realize.

The use SimpleDateFormat to format dates

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

Let's modify the above example, as follows:

package com.w3big.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 previous Servlet again, and then visit http: to call the Servlet 8080 / TomcatTest / CurrentDate: // localhost. This will produce the following results:


Simple date format code format

Using the Event mode string to specify the time format. In this mode, all ASCII letters are reserved as pattern letters, and the letters are defined as follows:

character description Examples
G Era indicator AD
y Four digit years 2001
M Month of the year Or July 07
d The first few days of the month 10
h AM / PM, hour (1 to 12) with 12
H The first few hours of the day (0 to 23) twenty two
m One hour of the first fraction 30
s One point in the first few seconds 55
S millisecond 234
E The week of the week Tuesday
D The first few days of the year 360
F Week is the week where this month 2 (second Wed. in July)
w The first few weeks of the year 40
W The first few weeks of January 1
a AM / PM mark PM
k The first few hours of the day (1 to 24) twenty four
K With AM / PM hour (0 to 11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" apostrophe `

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