📜  Servlet-处理日期

📅  最后修改于: 2020-11-12 05:43:34             🧑  作者: Mango


使用Servlet的最重要优点之一是,您可以使用Java核心中可用的大多数方法。本教程将带您浏览Java提供的Date类,该类在java.util包中可用,该类封装了当前日期和时间。

Date类支持两个构造函数。第一个构造函数使用当前日期和时间初始化对象。

Date( )

以下构造函数接受一个参数,该参数等于自1970年1月1日午夜以来经过的毫秒数

Date(long millisec)

一旦有Date对象可用,就可以调用以下任何一种支持方法来播放日期-

Sr.No. Methods & Description
1

boolean after(Date date)

Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.

2

boolean before(Date date)

Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.

3

Object clone( )

Duplicates the invoking Date object.

4

int compareTo(Date date)

Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.

5

int compareTo(Object obj)

Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.

6

boolean equals(Object date)

Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.

7

long getTime( )

Returns the number of milliseconds that have elapsed since January 1, 1970.

8

int hashCode( )

Returns a hash code for the invoking object.

9

void setTime(long time)

Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.

10

String toString( )

Converts the invoking Date object into a string and returns the result.

获取当前日期和时间

这很容易在Java Servlet中获取当前日期和时间。您可以将简单的Date对象与toString()方法一起使用,以打印当前日期和时间,如下所示:

// Import required java libraries
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class CurrentDate extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Display Current Date & Time";
      Date date = new Date();
      String docType = ""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
      
      out.println(docType +
         "\n" +
            "" + title + "\n" +
            "\n" +
               "

" + title + "

\n" + "

" + date.toString() + "

\n" + " " ); } }

现在,让我们在Servlet之上进行编译,并在web.xml中创建适当的条目,然后使用URL http:// localhost:8080 / CurrentDate调用此servlet。这将产生以下结果-

Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010

尝试刷新URL http:// localhost:8080 / CurrentDate,每次刷新的秒数都会有所不同。

日期比较

如前所述,您可以在Servlet中使用所有可用的Java方法。如果您需要比较两个日期,以下是方法-

  • 您可以使用getTime()获取两个对象自1970年1月1日午夜以来经过的毫秒数,然后比较这两个值。

  • 您可以使用before(),after()和equals()方法。例如,因为每月的12号早于18号,所以new Date(99,2,12).before(new Date(99,2,18))返回true。

  • 您可以使用compareTo()方法,该方法由Comparable接口定义,并由Date实现。

使用SimpleDateFormat格式化日期

SimpleDateFormat是一个具体的类,用于以对语言敏感的方式格式化和解析日期。 SimpleDateFormat允许您从选择任何用户定义的日期时间格式模式开始。

让我们修改上面的示例如下-

// Import required java libraries
import java.io.*;
import java.text.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class CurrentDate extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Display Current Date & Time";
      Date dNow = new Date( );
      SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
      String docType = ""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
      
      out.println(docType +
         "\n" +
            "" + title + "\n" +
            "\n" +
               "

" + title + "

\n" + "

" + ft.format(dNow) + "

\n" + " " ); } }

再次在上述servlet上进行编译,然后使用URL http:// localhost:8080 / CurrentDate调用此servlet。这将产生以下结果-

Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM GMT+04:00

简单的DateFormat格式代码

要指定时间格式,请使用时间模式字符串。在此模式中,所有ASCII字母均保留为模式字母,定义如下:

Character Description Example
G Era designator 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 `

有关操作日期的常量可用方法的完整列表,请参考标准Java文档。