使用 SimpleDateFormat 解析字串為 Date,取得毫秒時間戳相減,再換算天/時/分/秒:
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");
}
}
LocalDate start = LocalDate.parse("2023-01-01");
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end); // 直接得天數
// 含時間精度
LocalDateTime ldtStart = LocalDateTime.parse("2023-01-01T10:00:00");
LocalDateTime ldtEnd = LocalDateTime.now();
Duration d = Duration.between(ldtStart, ldtEnd);
long hours = d.toHours();
long minutes = d.toMinutesPart(); // Java 9+
long seconds = d.toSecondsPart();
建議新專案直接使用 java.time 套件,不可變、執行緒安全、API 直觀。