Java時間工具類
廢話不說,直接上程式碼:
/**
* 獲取過去第幾天的日期
*/
public static Date getPastDate(Date date, int past) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date pastDate = calendar.getTime();
return pastDate;
}
/**
* date2比date1多的天數
* @param date1
* @param date2
* @return
*/
public static int differentDays(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) // 同一年
{
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) // 閏年
{
timeDistance += 366;
} else // 不是閏年
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else // 不同年
{
System.out.println("判斷day2 - day1 : " + (day2 - day1));
return day2 - day1;
}
}
/**
* 獲取當前日期是星期幾
* @param dt
* @return 當前日期是星期幾
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0){
w = 0;
}
return weekDays[w];
}