在java中用到的最多的時間類莫過于 java.util.Date了, 由于Date類中將getYear(),getMonth()等獲取年、月、日的方法都廢棄了,所以要借助于Calendar來獲取年、月、日、周等比較常用的日期格式
注意:以下代碼均已在jdk1.6中測試通過,其他版本可能使用不同,請注意!
Date與String的互轉用法
1
2
3
4
5
6
7
|
/** * Date與String的互轉用法,這里需要用到SimpleDateFormat */ Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd" ); String dateString = formatter.format(currentTime); Date date = formatter.parse(dateString); |
Date與Calendar之間的互轉
1
2
3
4
5
6
|
/** * Date與Calendar之間的互轉 */ Calendar cal = Calendar.getInstance(); cal.setTime( new Date()); Date date1 = cal.getTime(); |
利用Calendar獲取年、月、周、日、小時等時間域
1
2
3
4
5
6
7
|
/** * 利用Calendar獲取年、月、周、日、小時等時間域 */ cal.get(Calendar.YEAR); cal.get(Calendar.MONTH); cal.get(Calendar.WEEK_OF_MONTH); cal.get(Calendar.DAY_OF_MONTH); |
對時間進行加減
1
2
3
4
5
|
/** * 對時間進行加減 */ cal.add(Calendar.MONTH, 1 ); System.out.println(cal.getTime()); |
算出給定日期是屬于星期幾
1
2
3
4
5
6
|
Calendarcal = Calendar.getInstance(); cal.set( 2016 , 08 , 01 ); String[] strDays = new String[] { "SUNDAY" , "MONDAY" , "TUESDAY" , "WEDNESDAY" , "THURSDAY" , "FRIDAY" , "SATURDAY" }; System.out.println(strDays[cal.get(Calendar.DAY_OF_WEEK) - 1 ]); |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/u014717036/article/details/52121866