Java中的日期和時間
Java在java.util包中提供了Date類,這個類封裝了當前的日期和時間。html
Date類支持兩種構造函數。第一個構造函數初始化對象的當前日期和時間。java
Date()
下面的構造函數接收一個參數等於自1970年1月1日午夜起已通過的毫秒數函數
Date(long millisec)
一旦有一個可用的日期對象,能夠調用如下任何一種支持的方法使用時間:url
方法 | 描述 |
---|---|
boolean after(Date date) | 若是調用Date對象包含或晚於指定的日期則返回true,不然,返回false。 |
boolean before(Date date) | 若是調用Date對象包含或早於日期指定的日期返回true,不然,返回false。 |
Object clone( ) | 重複調用Date對象。 |
int compareTo(Date date) | 調用對象的值與日期比較。若是這兩個值相等返回0。若是調用對象是早於日期返回一個負值。若是調用對象遲於日期返回正值。 |
int compareTo(Object obj) | 以相同的compareTo(Date)操做 若是obj是一個類日期。不然,它會拋出一個ClassCastException。 |
boolean equals(Object date) | 若是調用Date對象包含相同的時間及日期指定日期則返回true,不然,返回false。 |
long getTime( ) | 返回自1970年1月1日起已通過的毫秒數。 |
int hashCode( ) | 返回調用對象的哈希代碼。 |
void setTime(long time) | 設置所指定的時間,這表示從1970年1月1日從午夜的時間和日期以毫秒爲單位通過的時間。 |
String toString( ) | 調用Date對象轉換爲字符串,並返回結果。 |
1、獲取當前日期和時間spa
在Java中容易獲得當前的日期和時間。可使用一個簡單的Date對象的toString()方法,以下所示打印當前日期和時間:操作系統
import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); } } //這將產生如下結果: Wed May 31 15:20:32 CST 2017
2、日期比較.net
有如下三種方式來比較兩個日期:code
- 可使用getTime()來得到自1970年1月1日午夜十二時起已通過的毫秒數,而後比較兩個對象的值。
- 可使用before( ),after( ),和equals( )方法,因爲12日在18日前,例如,new Date(99, 2, 12).before(new Date (99, 2, 18))返回值爲true。
- 可使用compareTo()方法,這是由Comparable接口定義,由Date實現。
3、使用SimpleDateFormat格式化日期orm
SimpleDateFormat是一個具體的類,以本地方式用於格式化和轉換日期。SimpleDateFormat容許選擇用戶定義的模式爲日期時間格式。例如:htm
import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); } } //這將產生如下結果:
Current Date: 星期三 2017.05.31 at 03:22:48 下午 CST
4、簡單的DateFormat格式代碼
要指定時間格式,使用時間模式字符串。在這個模式中,全部的ASCII字母被保留爲模式字母,其定義以下:
字符 | 描述 | 例子 |
---|---|---|
G | 時代指示器 | AD |
y | 四位數年份 | 2001 |
M | 年中的月份 | July or 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 | 時區 | 東部標準時間 |
' | 脫離文本 | 分隔符 |
" | 單引號 | ` |
注意:有些中文版的操做系統返回值可能爲中文。
5、用printf格式化日期
日期和時間格式用printf方法能夠很是輕鬆地作到。可使用兩個字母的格式,從t
開始並在下面給出的表格中的其中一個字母結束。例如:
import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() String str = String.format("Current Date/Time : %tc", date ); System.out.printf(str); } } //這將產生如下結果: Current Date/Time : 星期三 五月 31 15:25:43 CST 2017
若是提供日期屢次格式化是一種很差的作法。一個格式字符串能夠指示要格式化的參數的索引。
索引必須緊跟在%以後,並必須由$終止。例如:
import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); } } //這將產生如下結果: Due date: 五月 31, 2017
或者,也可使用<標誌。則表示相同的參數,根據前述格式規範,應再次使用。例如:
import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display formatted date System.out.printf("%s %tB %<te, %<tY", "Due date:", date); } } //這將產生如下結果: Due date: 五月 31, 2017
6、日期和時間轉換字符
字符 | 描述 | 例子 |
---|---|---|
c | 完整的日期和時間 | Mon May 04 09:51:52 CDT 2009 |
F | ISO 8601 日期 | 2004-02-09 |
D | U.S. 格式時間 (月/日/年) | 02/09/2004 |
T | 24-時制 | 18:05:19 |
r | 12-時制 | 06:05:19 pm |
R | 24-時制,無秒 | 18:05 |
Y | 四位數年份 (用前行零列) | 2004 |
y | 年份的後兩位數(用前行零列) | 04 |
C | 年份的前兩位(用前行零列) | 20 |
B | 完整月份名稱 | February |
b | 縮寫月份名稱 | Feb |
m | 兩位數月份 (用前行零列) | 02 |
d | 兩位很多天期 (用前行零列) | 03 |
e | 兩位很多天期(無前行零列) | 9 |
A | 完整星期名稱 | Monday |
a | 縮寫星期名稱 | Mon |
j | 年中的三位數天數(用前行零列) | 069 |
H | 兩位數小時(用前行零列), 00 和 23之間 | 18 |
k | 兩位數小時(無前行零列), 0 和 23 之間 | 18 |
I | 兩位數小時 (用前行零列), 01和12之間 | 06 |
l | 兩位數小時 (無前行零列), 1 和12之間 | 6 |
M | 兩位數分鐘 (用前行零列) | 05 |
S | 兩位數秒鐘(用前行零列) | 19 |
L | 三位數毫秒(用前行零列) | 047 |
N | 九位數納秒 (用前行零列) | 047000000 |
P | 大寫上下午標記 | PM |
p | 小寫上下午標記 | pm |
z | RFC 822 從GMT數字抵消 | -0800 |
Z | 時區 | PST |
s | 從 1970-01-01 00:00:00 的秒數GMT | 1078884319 |
Q | 從 1970-01-01 00:00:00 的毫秒數GMT | 1078884319047 |
有相關的日期和時間等有用的類。欲瞭解更多詳細信息,能夠參考Java標準文檔。
7、字符串轉換日期
SimpleDateFormat類有一些額外的方法,如parse(),它試圖根據存儲在給定SimpleDateFormat的對象的格式來轉換字符串。例如:
import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); String input = args.length == 0 ? "1818-11-11" : args[0]; System.out.print(input + " Parses as "); Date t; try { t = ft.parse(input); System.out.println(t); } catch (ParseException e) { System.out.println("Unparseable using " + ft); } } } //上述程序的運行示例將產生如下結果: $ java DateDemo 1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818 $ java DateDemo 2007-12-01 2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007
8、休眠一段時間
能夠進行任何期間的時間休眠,從一毫秒直到電腦的整個生命週期。例如,下面的程序會休眠10秒:
import java.util.*; public class SleepDemo { public static void main(String args[]) { try { System.out.println(new Date( ) + "\n"); Thread.sleep(5*60*10); System.out.println(new Date( ) + "\n"); } catch (Exception e) { System.out.println("Got an exception!"); } } } //這將產生如下結果: Wed May 31 15:37:56 CST 2017 Wed May 31 15:37:59 CST 2017
9、測量執行時間
有時候,可能須要測量的時間點以毫秒爲單位。所以,從新寫上面的例子:
import java.util.*; public class DiffDemo { public static void main(String args[]) { try { long start = System.currentTimeMillis( ); System.out.println(new Date( ) + "\n"); Thread.sleep(5*60*10); System.out.println(new Date( ) + "\n"); long end = System.currentTimeMillis( ); long diff = end - start; System.out.println("Difference is : " + diff); } catch (Exception e) { System.out.println("Got an exception!"); } } } //這將產生如下結果:
Wed May 31 15:38:58 CST 2017
Wed May 31 15:39:01 CST 2017
Difference is : 3013
10、GregorianCalendar類
GregorianCalendar是一個Calendar類具體的實現,即對正常Gregorian公曆的實現。
Calendar的getInstance()方法返回與當前日期和時間默認語言環境和時區初始化的一個GregorianCalendar。GregorianCalendar中定義了兩個字段:AD和BC。這些表明在公曆中定義的兩個時代。
也有幾個構造函數的GregorianCalendar對象:
構造函數 | 描述 |
---|---|
GregorianCalendar() | 在默認時區與默認語言環境使用當前時間構造默認的GregorianCalendar。 |
GregorianCalendar(int year, int month, int date) | 在默認時區設置默認的語言環境用給定的日期構造一個GregorianCalendar |
GregorianCalendar(int year, int month, int date, int hour, int minute) | 用給定的日期和時間設置爲與默認語言環境的默認時區構造一個GregorianCalendar。 |
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) | 用給定的日期和時間設置爲與默認語言環境的默認時區構造一個 GregorianCalendar |
GregorianCalendar(Locale aLocale) | 基於當前時間與給定語言環境的默認時區構建一個GregorianCalendar。 |
GregorianCalendar(TimeZone zone) | 基於當前時間,使用默認的語言環境在給定的時區構建一個GregorianCalendar。 |
GregorianCalendar(TimeZone zone, Locale aLocale) | 基於當前時間與給定語言環境的給定時區構建一個GregorianCalendar。 |
這裏是由GregorianCalendar類提供的一些有用的方法的列表:
方法 | 描述 |
---|---|
void add(int field, int amount) | 基於日曆的規則,以給定的時間字段添加指定(有符號的)時間量。 |
protected void computeFields() | 將UTC轉換爲毫秒時間字段值. |
protected void computeTime() | 覆蓋日曆轉換時間域值爲UTC的毫秒. |
boolean equals(Object obj) | 這個GregorianCalendar與一個對象引用比較. |
int get(int field) | 獲取給定時間域的值. |
int getActualMaximum(int field) | 返回該字段可能的最大值,給定到當前的日期. |
int getActualMinimum(int field) | 返回該字段可能具備的最小值,給定當前的日期. |
int getGreatestMinimum(int field) | 對於給定的字段中返回高最低值(若是有變化). |
Date getGregorianChange() | 獲取公曆更改日期. |
int getLeastMaximum(int field) | 對於給定的字段返回最低的最大值,若是有變化. |
int getMaximum(int field) | 返回給定字段中的最大值. |
Date getTime() | 獲取日曆的當前時間. |
long getTimeInMillis() | 獲取日曆的當前時間長. |
TimeZone getTimeZone() | 獲取時區. |
int getMinimum(int field) | 返回給定字段中的最小值. |
int hashCode() | 重寫hashCode. |
boolean isLeapYear(int year) | 肯定給定年份是閏年. |
void roll(int field, boolean up) | 加上或減去(上/下)的時間在給定的時間字段一個單元,不更改更大的字段. |
void set(int field, int value) | 設置時間字段與給定值. |
void set(int year, int month, int date) | 設置爲年,月,日的值. |
void set(int year, int month, int date, int hour, int minute) | 設置爲年,月,日,小時和分鐘值. |
void set(int year, int month, int date, int hour, int minute, int second) | 設置爲字段的年,月,日,小時,分鐘和秒的值. |
void setGregorianChange(Date date) | 設置GregorianCalendar更改日期. |
void setTime(Date date) | 設置日曆的當前時間與給定日期. |
void setTimeInMillis(long millis) | 從給定long值設置日曆的當前時間. |
void setTimeZone(TimeZone value) | 將時區設置與給定的時區值. |
String toString() | 返回此日曆的字符串表示形式. |
示例:
import java.util.*; public class GregorianCalendarDemo { public static void main(String args[]) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int year; // Create a Gregorian calendar initialized // with the current date and time in the // default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar(); // Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } } } //這將產生如下結果:
Date: May 31 2017
Time: 3:44:49
The current year is not a leap year
在Calendar類中的可用常量的完整列表,能夠參考標準的Java文檔。