在java中用到的最多的時間類莫過於 java.util.Date了,
由於Date類中將getYear(),getMonth()等獲取年、月、日的方法都廢棄了,
所以要藉助於Calendar來獲取年、月、日、周等比較常用的日期格式
注意:以下代碼均已在jdk1.6中測試通過,其他版本可能使用不同,請注意!
Date與String的相互轉換
/** * 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之間的互轉
/** * Date與Calendar之間的互轉 */Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); Date date1 = cal.getTime();
利用Calendar獲取年、月、周、日、小時等時間域
/** * 利用Calendar獲取年、月、周、日、小時等時間域 */cal.get(Calendar.YEAR); cal.get(Calendar.MONTH); cal.get(Calendar.WEEK_OF_MONTH); cal.get(Calendar.DAY_OF_MONTH);
對時間進行加減
/** * 對時間進行加減 */cal.add(Calendar.MONTH, 1); System.out.println(cal.getTime());
算出給定日期是屬於星期幾
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]);