封裝常見日期運算:本週/上週/下週、本月/上月/下月、本年/上年/下年、季度、間隔天數、星期幾等。
| 方法 | 功能 | 回傳格式 |
|---|---|---|
| getNowTime(pattern) | 當前時間格式化 | String |
| getMondayOFWeek() | 本週一日期 | yyyy-MM-dd |
| getCurrentWeekday() | 本週日日期 | yyyy-MM-dd |
| getPreviousWeekday() | 上週一日期 | yyyy-MM-dd |
| getPreviousWeekSunday() | 上週日日期 | yyyy-MM-dd |
| getNextMonday() | 下週一日期 | yyyy-MM-dd |
| getNextSunday() | 下週日日期 | yyyy-MM-dd |
| getFirstDayOfMonth() | 本月第一天 | yyyy-MM-dd |
| getDefaultDay() | 本月最後一天 | yyyy-MM-dd |
| getPreviousMonthFirst() | 上月第一天 | yyyy-MM-dd |
| getPreviousMonthEnd() | 上月最後一天 | yyyy-MM-dd |
| getNextMonthFirst() | 下月第一天 | yyyy-MM-dd |
| getNextMonthEnd() | 下月最後一天 | yyyy-MM-dd |
| getCurrentYearFirst() | 本年第一天 | yyyy-MM-dd |
| getCurrentYearEnd() | 本年最後一天 | yyyy-MM-dd |
| getThisSeasonTime(month) | 指定月份所屬季度首尾 | yyyy-MM-dd;yyyy-MM-dd |
| getTwoDay(d1, d2) | 兩日期間隔天數 | String(天數) |
| getWeek(dateStr) | 日期對應星期幾 | 中文星期幾 |
private int getMondayPlus() {
Calendar cd = Calendar.getInstance();
// Calendar.DAY_OF_WEEK: 1=週日 ... 7=週六
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 轉為 0=週一 ... 6=週日
if (dayOfWeek == 1) return 0; // 今天就是週一
return 1 - dayOfWeek; // 負數表示往前推
}
// 本週一
currentDate.add(Calendar.DATE, mondayPlus);
// 本週日
currentDate.add(Calendar.DATE, mondayPlus + 6);
// 本月第一天
cal.set(Calendar.DATE, 1);
// 本月最後一天:下月 1 號減 1 天
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
// 上月第一天
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
// 上月最後一天:本月 1 號減 1 天
cal.add(Calendar.DATE, -1);
// 本年第一天
cal.set(Calendar.DAY_OF_YEAR, 1);
// 本年最後一天:明年第一天減 1 天
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
int[][] quarters = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
int season = (month - 1) / 3; // 0-based
int startMonth = quarters[season][0];
int endMonth = quarters[season][2];
// 利用 getLastDayOfMonth 取得結束日
public boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2023-05-20"); // String → Date
String str = sdf.format(date); // Date → String
新專案強烈建議使用 java.time(JSR-310),API 更清晰、不可變、線程安全:
LocalDate today = LocalDate.now();
LocalDate monday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate monthEnd = today.with(TemporalAdjusters.lastDayOfMonth());
long daysBetween = ChronoUnit.DAYS.between(start, end);
文中提供的 TimeTest 類可直接複製使用,主方法已包含所有功能演示輸出。