整理常用日期操作靜態方法,基於 SimpleDateFormat、Calendar(JDK 7 風格),JDK 8+ 建議改用 java.time 套件。
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class DateUtils {
private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_PATTERN = "yyyy-MM-dd";
private static final String HOUR_PATTERN = "yyyy-MM-dd HH";
/** 1. 比較兩個日期字串大小
* @return 1: date1 > date2, -1: date1 < date2, 0: 相等 */
public static int compareDate(String date1, String date2) {
DateFormat df = new SimpleDateFormat(DATETIME_PATTERN);
try {
Date d1 = df.parse(date1);
Date d2 = df.parse(date2);
long diff = d1.getTime() - d2.getTime();
return Long.compare(diff, 0);
} catch (ParseException e) {
throw new IllegalArgumentException("日期格式錯誤", e);
}
}
/** 2. 計算兩個日期相差天數 (忽略時分秒) */
public static int daysBetween(String startDate, String endDate) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
Calendar cal = Calendar.getInstance();
try {
cal.setTime(sdf.parse(startDate));
long t1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endDate));
long t2 = cal.getTimeInMillis();
return (int) ((t2 - t1) / (1000 * 3600 * 24));
} catch (ParseException e) {
throw new IllegalArgumentException("日期格式錯誤", e);
}
}
/** 3. 計算兩個日期時間相差小時數 */
public static int hoursBetween(String startTime, String endTime) {
SimpleDateFormat sdf = new SimpleDateFormat(HOUR_PATTERN);
Calendar cal = Calendar.getInstance();
try {
cal.setTime(sdf.parse(startTime));
long t1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endTime));
long t2 = cal.getTimeInMillis();
return (int) ((t2 - t1) / (1000 * 3600));
} catch (ParseException e) {
throw new IllegalArgumentException("日期格式錯誤", e);
}
}
/** 4. 計算兩個日期區間的重疊部分
* @return Map 包含 startDate、endDate (重疊區間),無重疊返回空字串 */
public static Map<String, String> overlap(String s1, String e1, String s2, String e2) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
Map<String, String> result = new HashMap<>();
result.put("startDate", "");
result.put("endDate", "");
try {
Date d1 = sdf.parse(s1);
Date d2 = sdf.parse(e1);
Date d3 = sdf.parse(s2);
Date d4 = sdf.parse(e4);
long maxStart = Math.max(d1.getTime(), d3.getTime());
long minEnd = Math.min(d2.getTime(), d4.getTime());
if (maxStart <= minEnd) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxStart);
result.put("startDate", sdf.format(c.getTime()));
c.setTimeInMillis(minEnd);
result.put("endDate", sdf.format(c.getTime()));
}
} catch (ParseException ex) {
throw new IllegalArgumentException("日期格式錯誤", ex);
}
return result;
}
}
public static void main(String[] args) {
System.out.println(DateUtils.compareDate("2023-01-01 10:00:00", "2023-01-01 09:00:00")); // 1
System.out.println(DateUtils.daysBetween("2023-01-01", "2023-01-10")); // 9
System.out.println(DateUtils.hoursBetween("2023-01-01 10", "2023-01-01 15")); // 5
Map<String, String> ov = DateUtils.overlap("2023-01-01", "2023-01-10", "2023-01-05", "2023-01-15");
System.out.println("重疊: " + ov.get("startDate") + " ~ " + ov.get("endDate")); // 2023-01-05 ~ 2023-01-10
}
// 比較
LocalDateTime d1 = LocalDateTime.parse("2023-01-01T10:00:00");
LocalDateTime d2 = LocalDateTime.parse("2023-01-01T09:00:00");
int cmp = d1.compareTo(d2);
// 差天數
long days = ChronoUnit.DAYS.between(LocalDate.parse("2023-01-01"), LocalDate.parse("2023-01-10"));
// 差小時
long hours = ChronoUnit.HOURS.between(
LocalDateTime.parse("2023-01-01T10:00"), LocalDateTime.parse("2023-01-01T15:00"));
// 區間重疊
LocalDate maxStart = LocalDate.parse("2023-01-01").isAfter(LocalDate.parse("2023-01-05")) ?
LocalDate.parse("2023-01-01") : LocalDate.parse("2023-01-05");
// ... 類似邏輯
java.time 不可變、執行緒安全、API 豐富,新專案優先採用。