1. 程式人生 > >與時間有關的類Date,DateFormat,Calendar

與時間有關的類Date,DateFormat,Calendar

輸出 操作 calendar類 ack catch tex hour main 表示

Date類用於表示日期和時間。它沒考慮國際化問題,所以又設計了另外兩個類。

Calendar類:

主要是進行日期字段之間的相互操作。

編程實例:計算出距當前日期時間315天後的日期時間,並使用”xxxx年xx月xx日xx小時:xx分:xx秒”的格式輸出。

import java.util.*;

import java.text.SimpleDateFormat; //由於simpledateformat和dateformat在這個包中

public class TestCalendar

{

public static void main(String[] args)

{

Calendar cl=Calendar.getInstance(); //創建一個實例

System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+cl.get(cl.DAY_OF_MONTH)+"日 "+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND));

/*

使用get方法來取得日期中的年月日等等,參數為類中的常數,可以直接使用類名調用常數,也可以使用對象名。

*/

cl.add(cl.DAY_OF_MONTH,315);

//加上315天,使用add方法,第一個參數為單位,也是常數。

System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+cl.get(cl.DAY_OF_MONTH)+"日 "+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND));

SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd"); //定義了格式

SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日"); //定義了格式

try

{

Date d=sdf1.parse("2003-03-15"); //將字符串強制轉換成這種格式,使用parse()

System.out.println(sdf2.format(d));將格式1的日期轉換成格式2,使用format()

}

catch(Exception e)

{

e.printStackTrace();

}

}

}

編程實例:將“2002-03-15“格式的日期轉換成“2003年03月15日”的格式。代碼在上例中的黑體部分。

與時間有關的類Date,DateFormat,Calendar