public class DateDiffUtil {
public static void dateDiff(String startTime, String endTime, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
long nd = 1000L * 24 * 60 * 60; // 一天毫秒數
long nh = 1000L * 60 * 60; // 一小時毫秒數
long nm = 1000L * 60; // 一分鐘毫秒數
long ns = 1000L; // 一秒毫秒數
try {
long diff = sdf.parse(endTime).getTime() - sdf.parse(startTime).getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
long sec = diff % nd % nh % nm / ns;
System.out.printf("時間相差:%d天 %d小時 %d分鐘 %d秒。%n", day, hour, min, sec);
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 範例:計算今天到 2010-08-23 相差
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
dateDiff(today, "2010-08-23", "yyyy-MM-dd");
}
}
ThreadLocal 或 Java 8 DateTimeFormatter。Date.getTime() 取得 UTC 毫秒數相減。ParseException,實際專案建議拋出自訂異常或回傳 Optional。import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class ModernDateDiff {
public static void dateDiff(String start, String end, String pattern) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
LocalDateTime s = LocalDateTime.parse(start, fmt);
LocalDateTime e = LocalDateTime.parse(end, fmt);
long days = ChronoUnit.DAYS.between(s, e);
long hours = ChronoUnit.HOURS.between(s, e) % 24;
long minutes = ChronoUnit.MINUTES.between(s, e) % 60;
long seconds = ChronoUnit.SECONDS.between(s, e) % 60;
System.out.printf("時間相差:%d天 %d小時 %d分鐘 %d秒。%n", days, hours, minutes, seconds);
}
}
java.time 套件不可變、執行緒安全、API 豐富(Period、Duration、ChronoUnit)。無論使用傳統 SimpleDateFormat 或現代 java.time,核心邏輯皆為「取得時間點差值 → 分解單位」。掌握兩種寫法,可依專案 JDK 版本靈活選擇。