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

來源:互聯網
上載者:User

標籤:

1. Calendar是個抽象類別,靜態方法getInstance() 可以得到它的一個執行個體

Calendar ca = Calendar.getInstance();
ca.set(2015, 10,20);//通過set可以設定Year、Month、date、hour、minute、second,注意月是從0開始的0-11(不設定則預設為系統目前時間);

System.out.println(ca.get(Calendar.YEAR));//通過get(Calendar.XXX)可以拿到相應年月日時分秒;

以下方法可以用來獲得當前是這一XX的第幾天:

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

2. Calendar和Date的轉化

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

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

3. 格式化輸出日期時間

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

 4. Date

現在,讓我們如何看看添加小時到一個date對象。所有在date上的日期操作都需要通過添加毫秒到date才能完成。例如,如果我們想增加6個小時,那麼我們需要將6小時換算成毫秒。6小時= 6 * 60 * 60 * 1000毫秒。請看以下的例子。 

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

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

//Formatting DatesSystem.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 2012System.out.println(DateFormat.getDateInstance(        DateFormat.FULL, Locale.ITALIAN)        .format(date));//marted“ 16 ottobre 2012//This uses default locale USSystem.out.println(DateFormat.getDateInstance(        DateFormat.FULL).format(date));//Tuesday, October 16, 2012System.out.println(DateFormat.getDateInstance()        .format(date));//Oct 16, 2012System.out.println(DateFormat.getDateInstance(        DateFormat.SHORT).format(date));//10/16/12System.out.println(DateFormat.getDateInstance(        DateFormat.MEDIUM).format(date));//Oct 16, 2012System.out.println(DateFormat.getDateInstance(        DateFormat.LONG).format(date));//October 16, 2012

 

 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.