English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Uno dei principali vantaggi dell'uso di Servlet è che si possono utilizzare la maggior parte dei metodi disponibili in Java core. Questo capitolo spiega i seguenti forniti da Java: java.util Del pacchetto Date Classe, questa classe avvolge la data e l'ora corrente.
La classe Date supporta due costruttori. Il primo costruttore inizializza l'oggetto con la data e l'ora corrente.
Date( )
I seguenti costruttori accettano un parametro che rappresenta il numero di millisecondi trascorsi dal mezzanotte del 1 gennaio 1970.
Date(long millisec)
Una volta che avete un oggetto Date disponibile, potete chiamare uno dei seguenti metodi supportati per utilizzare la data:
Numero di sequenza | Metodo & Descrizione |
---|---|
1 | boolean after(Date date) Se l'oggetto Date chiamato contiene una data dopo la data specificata da date, restituisce true, altrimenti restituisce false. |
2 | boolean before(Date date) Se l'oggetto Date chiamato contiene una data prima della data specificata da date, restituisce true, altrimenti restituisce false. |
3 | Object clone( ) Chiamata ripetuta dell'oggetto Date. |
4 | int compareTo(Date date) Confronta il valore dell'oggetto chiamato con il valore di date. Se i due valori sono uguali, restituisce 0. Se l'oggetto chiamato è prima di date, restituisce un valore negativo. Se l'oggetto chiamato è dopo date, restituisce un valore positivo. |
5 | int compareTo(Object obj) Se obj è una classe Date, l'operazione è equivalente a compareTo(Date). Altrimenti, lancia un ClassCastException. |
6 | boolean equals(Object date) Restituisce true se l'oggetto Date chiamato contiene la data e l'ora esatta specificata in date, altrimenti restituisce false. |
7 | long getTime( ) Restituisce i millisecondi trascorsi dal 1 gennaio 1970. |
8 | int hashCode( ) Restituisce un codice hash per l'oggetto chiamato. |
9 | void setTime(long time) Imposta il tempo e la data specificati con time, che rappresenta il tempo trascorso dal 1 gennaio 1970 mezzanotte (in millisecondi). |
10 | String toString( ) Converti l'oggetto Date chiamato in una stringa e restituisci il risultato. |
E' molto facile ottenere la data e l'ora corrente in un Servlet Java. Puoi usare un semplice oggetto Date: toString() Metodo per output la data e l'ora corrente, come segue:
package com.w3codebox.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 = "Visualizza la data e l'ora corrente"; 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>); } }
Ora, lasciatoci compilare il seguente Servlet e creare l'entry appropriata nel file web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>CurrentDate</servlet-name> <servlet-class>com.w3codebox.test.CurrentDate</servlet-class> </servlet> <servlet-mapping> <servlet-name>CurrentDate</servlet-name> <url-pattern>/TomcatTest/CurrentDate</url-pattern> </servlet-mapping> </web-app>
Poi chiama il Servlet tramite l'accesso a http://localhost:8080/TomcatTest/CurrentDate. Questo produrrà il seguente risultato:
Prova a ricaricare l'URL http://localhost:8080/TomcatTest/CurrentDate, ogni volta che ricarichi ogni pochi secondi noterai una differenza nell'ora visualizzata.
Come menzionato sopra, puoi usare tutti i metodi Java disponibili nel Servlet. Se devi confrontare due date, ecco un esempio di metodo:
Puoi usare getTime() per ottenere il tempo trascorso da mezzanotte del 1° gennaio 1970 in millisecondi per due oggetti, quindi confrontare questi valori.
Puoi usare i metodi before(), after() e equals(). Poiché il 12° giorno di un mese è prima del 18°, ad esempio, new Date(99, 2, 12).before(new Date(99, 2, 18)) restituisce true.
Puoi usare il metodo compareTo() definito dall'interfaccia Comparable, implementato da Date.
SimpleDateFormat è una classe specifica per formattare e解析日期,它对语言环境敏感。SimpleDateFormat vi permette di scegliere qualsiasi modello di formattazione della data e dell'ora definito dall'utente.
Modifichiamo l'esempio sopra, come segue:
package com.w3codebox.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 = "Visualizza la data e l'ora corrente"; Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd \t 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>); } }
Ricompila il Servlet sopra indicato e poi chiama il Servlet tramite l'accesso a http://localhost:8080/TomcatTest/CurrentDate. Questo produrrà il seguente risultato:
使用事件模式字符串来指定时间格式。在这种模式下,所有的 ASCII 字母被保留为模式字母,这些字母定义如下:
字符 | 描述 | 示例 |
---|---|---|
G | Era 指示器 | AD |
y | 四位数表示的年 | 2001 |
M | 一年中的月 | July 或 07 |
d | 一月中的第几天 | 10 |
h | 带有 A.M./P.M. 的小時(1~12) | 12 |
H | 一天中的第几小时(0~23) | 22 |
m | 一小时中的第几分 | 30 |
s | 一分中的第几秒 | 55 |
S | 毫秒 | 234 |
E | 一周中的星期几 | Tuesday |
D | 一年中的第几天 | 360 |
F | 所在的周是这个月的第几周 | 2 (second Wed. in July) |
w | 一年中的第几周 | 40 |
W | 一月中的第几周 | 1 |
a | A.M./P.M. 标记 | PM |
k | 一天中的第几小时(1~24) | 24 |
K | 帶有 A.M./P.M. 的小時(0~11) | 10 |
z | 時區 | Eastern Standard Time |
' | Escape for text | Delimiter |
" | 單引號 | ` |
如需查看可用的处理日期方法的完整列表,您可以參考標準的 Java 文檔。