Java中常用日期處理類

前言

日期處理在Java中一塊非常複雜的內容,包含日期的國際化,日期和時間的轉換,日期的加減運算,日期的展示格式等問題。而且在一些面試中也可能會有問到,所以整理了一下這部分的內容。主要涉及以下四個類:

  1. Date
  2. Calendar
  3. DateFormat
  4. SimpleDateFormat

由於Date類算是比較常用的,所以這裏只整理了後面的3個類。

Calendar 類

它是一個抽象類,它爲特定瞬間與一組諸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日曆字段之間的轉換提供了一些方法,併爲操作日曆字段(例如獲得下星期的日期)提供了一些方法。

獲取Calendar類的通用的對象

Calendar 提供了一個類方法 getInstance,以獲得此類型的一個通用對象。

Calendar now = Calendar.getInstance();

獲得並設置日曆字段的方法

Calendar可以調用set等方法來設置日曆字段的字段值,調用 getgetTimeInMillsgetTime等方法設置日曆字段。

Calendar cal Calendar.getInstance();
cal.setTime(new Date());
int year = cal.get(Calendar.YEAR);
int month = (cal.get(Calendar.MONTH))+1; //從0開始計算
System.out.println(cal.getTime());//輸出 Wed Jul 03 12:49:38 CST 2019
System.out.println(year);//輸出2019
System.out.println(month);//輸出7

日曆進行加減法

在Calendar對象的使用**add方法進行時間的加減操作**,其中第二個參數爲正數表示“加”,負數表示“減”。
下面是Calendar類中add方法的定義:

/**
     * Adds or subtracts the specified amount of time to the given calendar field,
     * based on the calendar's rules. For example, to subtract 5 days from
     * the current time of the calendar, you can achieve it by calling:
     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
     *
     * @param field the calendar field.
     * @param amount the amount of date or time to be added to the field.
     * @see #roll(int,int)
     * @see #set(int,int)
     */

	/**
	* 翻譯如下:
	* 根據日曆的規則,將指定的時間量添加或減去給定的日曆字段。
	* 例如,要從日曆的當前時間減去5天,可以通過調用:add(Calendar.DAY_OF_MONTH,-5)來實現它。
	* @param字段日曆字段。
	* @param爲要添加到字段的日期或時間量。
	**/
    abstract public void add(int field, int amount);

通過實例例子來使用一下add方法

Calendar cal Calendar.getInstance();
cal.setTime(new Date());
System.out.println(cal.getTime());//輸出 Wed Jul 03 12:49:38 CST 2019
cal.add(Calendar.YEAR,-1);//日期減1年
cal.add(Calendar.MONTH,3);//日期加3個月
cal.add(Calendar.DAY_OF_MONTH,10);//日期加10天
System.out.println(cal.getTime());//輸出Sat Oct 13 12:55:14 CST 2018
System.out.println(cal.get(Calendar.YEAR));//2018
System.out.println(cal.get(Calendar.MONTH));//9
System.out.println(cal.get(Calendar.DAY_OF_MONTH));//13

DataFormat 類

DataFormat是對日期/時間格式化的抽象類,它可以格式化或解析日期或時間,即允許將時間對象進行相互的轉換。

獲取DataFormat對象實例

DataFormat是抽象類,不能創建該類的對象,需要使用靜態方法 getDataInstancegetTimeInstancegetDataTimeInstance來得到日期時間格式對象

DataFormat df = DataFormat.getDataInstance(); 
//或者
DataFormat df1 = DataFormat.getDateInstance(DateFormat.LONG,LONG FRANCE);

日期格式化字符串

將日期、時間格式化爲字符串,主要使用**format**方法。例如

DataFormat df = DataFormat.getDataInstance(); 
String dfStr = df.format(new Date());

字符串解析爲日期

將字符串解析爲日期,主要使用**parse**方法。 例如

DataFormat df = DataFormat.getDataInstance(); 
Date d1 = df.parse("2019-7-3")

SimpleDateFormat 類

SimpleDateFormatDateFormat的子類,該類在包 java.text中,該類允許用戶自定義的日期-時間格式的模式,並利用此模式來顯示日期和時間

SimpleDateFormat 對象的創建

使用**new**關鍵字創建SimpleDateFormat類對象,例如

SimpleDateFormat fmt1 = new SimpleDateFormat();
SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat fmt3 = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒");

格式化日期時間對象

SimpleDateFormat類提供**format**方法來格式化日期和時間對象,例如:

Date now = new Date();
String str1 = fm1.format(now);

解析字符串爲日期對象

SimpleDateFormat類提供**parse**方法來解析字符串爲日期和時間對象,返回Date對象。例如:

Date d1 = fmt1.parse("2019-07-03");

完整例子

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Calen {
	public static void main(String[] args) throws ParseException {
		
		// 使用不同的日期時間方式初始化對象
		SimpleDateFormat fmt1 = new SimpleDateFormat();
		SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat fmt3 = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒 E");

		Date now = new Date();
		
		// 利用format將時間日期對象用不同的形式顯示出來
		System.out.println(fmt1.format(now));
		System.out.println(fmt2.format(now));
		System.out.println(fmt3.format(now));
		
		// 使用parse解析爲時間日期對象
		SimpleDateFormat fmt4 = new SimpleDateFormat("yyyy-MM-dd");
		Date d1 = fmt4.parse("2019-07-03");// 這裏的格式需要與上面的字符串格式相同
		System.out.println(d1);
	}
}

常用的模式字符串

在日期和時間模式字符串中,未加引號的字母 ‘A’ 到 ‘Z’ 和 ‘a’ 到 ‘z’ 被解釋爲模式字母,用來表示日期或時間字符串元素。
定義了以下模式字母(所有其他字符 ‘A’ 到 ‘Z’ 和 ‘a’ 到 ‘z’ 都被保留):

字母 日期或時間元素
Y 年Year
M 年中的月份
w 年中的週數
W 月份中的週數
D 年中的天數
d 月份中的天數
F 月份中的星期
E 星期中的天數
H 一天中的小時數(0~23)
k 一天中的小時數(1~24)
K am/pm 中的小時數(0~11)
h am/pm 中的小時數(1~12)
m 小時鐘的分鐘數
s 分鐘中的秒數
S 毫秒數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章