Java中的日期與時間(Date,Calendar)

1. Calendar是個抽象類,靜態方法getInstance() 能夠獲得它的一個實例 spa

Calendar ca = Calendar.getInstance();
ca.set(2015, 10,20);//經過set能夠設置Year、Month、date、hour、minute、second,注意月是從0開始的0-11(不設置則默認爲系統當前時間);
code

System.out.println(ca.get(Calendar.YEAR));//經過get(Calendar.XXX)能夠拿到相應年月日時分秒; orm

如下方法能夠用來得到當前是這一XX的第幾天: 對象

get(Calendar.DAY_OF_MONTH)得到這個月的第幾天
get(Calendar.DAY_OF_WEEK)得到這個星期的第幾天
get(Calendar.DAY_OF_YEAR)得到這個年的第幾天
getTimeMillis()得到當前時間的毫秒錶示

2. Calendar和Date的轉化 get

(1)Date date = cal.getTime(); it

(2)Date date = new Date();cal.setTime(date); form

3. 格式化輸出日期時間 date

Date date = new Date() ; 方法

SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss");//月份MM大寫以與分鐘mm區分;
System.out.println(sdf.format(date));//15-07-31 07:51:25
im

 4. Date

如今,讓咱們如何看看添加小時到一個date對象。全部在date上的日期操做都須要經過添加毫秒到date才能完成。例如,若是咱們想增長6個小時,那麼咱們須要將6小時換算成毫秒。6小時= 6 * 60 * 60 * 1000毫秒。請看如下的例子。 

Date date = new Date();

//Increase time by 6 hrs
date.setTime(date.getTime() + 6 * 60 * 60 * 1000);
System.out.println(date);

//Decrease time by 6 hrs
date = new Date();
date.setTime(date.getTime() - 6 * 60 * 60 * 1000);
System.out.println(date);

格式化日期須要使用DateFormat類完成。讓咱們看幾個例子。

//Formatting Dates
System.out.println(DateFormat.getInstance().format(
        date));//10/16/12 5:18 AM

帶有區域設置的格式化日期以下所示:

System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL, new Locale("it", "IT"))
        .format(date));//marted“ 16 ottobre 2012

System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL, Locale.ITALIAN)
        .format(date));//marted“ 16 ottobre 2012

//This uses default locale US
System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL).format(date));//Tuesday, October 16, 2012

System.out.println(DateFormat.getDateInstance()
        .format(date));//Oct 16, 2012
System.out.println(DateFormat.getDateInstance(
        DateFormat.SHORT).format(date));//10/16/12
System.out.println(DateFormat.getDateInstance(
        DateFormat.MEDIUM).format(date));//Oct 16, 2012

System.out.println(DateFormat.getDateInstance(
        DateFormat.LONG).format(date));//October 16, 2012
相關文章
相關標籤/搜索