| 方法 | 說明 |
|---|---|
str2Date(String, String) | 字串解析為 Date,第二參數為 pattern |
date2Str(Date, String) | Date 格式化輸出字串 |
changeDate(Date, "year|month|date", int) | 日期加減,支援年/月/日 |
getBeforeDate(Date, int) | 取得 N 天前日期 |
getLastWeekStart/End(Date) | 上週一/週日 (以週一為週首) |
getday(month, year) | 該年該月天數 |
patienage(start, end, type) | type=1 回傳「X年Y月Z天」,type=0 回傳總天數 |
getTime(String) | 日期字串轉 Unix 秒時間戳 |
checkTime(String, String) | 當前時間是否在每日 HH:mm 區間 |
checkDate(String, String) | 當前時間是否在完整日期區間 |
formatDate(Date) | 正規化為 00:00:00 |
Date now = new Date();
System.out.println(DateUtil.date2Str(now, "yyyy-MM-dd HH:mm:ss"));
// 2024-05-20 14:30:00
Date d = DateUtil.str2Date("2024-12-25", "yyyy-MM-dd");
System.out.println(DateUtil.changeDate(d, "month", -1));
// 2024-11-25 00:00:00
System.out.println(DateUtil.patienage(
DateUtil.str2Date("2000-01-01", "yyyy-MM-dd"), new Date(), 1));
// 24年4月19天
System.out.println(DateUtil.checkTime("09:00", "18:00")); // 上班時間判斷
Calendar.getInstance() 重新取得,避免狀態汙染。sync 鎖字串並重新賦值會導致鎖失效 (見同專案其他文章),本類未涉及同步。LocalDate, DateTimeFormatter, ChronoUnit 等不可變、執行緒安全、API 更豐富。
// 解析
LocalDate ld = LocalDate.parse("2024-05-20", DateTimeFormatter.ISO_LOCAL_DATE);
// 加減
LocalDate ld2 = ld.minusMonths(1);
// 差值
long days = ChronoUnit.DAYS.between(ld, LocalDate.now());
// 格式化
String out = ld2.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
新專案優先使用 java.time,舊專案維護可沿用本 DateUtil。