import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeUtils {
private static final String FORMAT = "yyyy.MM.dd HH:mm:ss";
private static final SimpleDateFormat SDF = new SimpleDateFormat(FORMAT);
/**
* 比較兩個時間字符串,返回秒差 (time2 - time1)
*/
public static long compare(String time1, String time2) {
Date d1 = SDF.parse(time1, new ParsePosition(0));
Date d2 = SDF.parse(time2, new ParsePosition(0));
if (d1 == null || d2 == null) return -1;
return (d2.getTime() - d1.getTime()) / 1000L;
}
/**
* 比較指定時間與當前時間,返回秒差 (now - time1)
*/
public static long compareNow(String time1) {
Date d1 = SDF.parse(time1, new ParsePosition(0));
if (d1 == null) return -1;
return (System.currentTimeMillis() - d1.getTime()) / 1000L;
}
}
// 計算兩時間差
long diff = DateTimeUtils.compare("2023.01.01 12:00:00", "2023.01.01 12:05:30"); // 330
// 計算距今秒數
long ago = DateTimeUtils.compareNow("2023.01.01 12:00:00"); // 當前時間減去該時間的秒數
SimpleDateFormat 非線程安全,此處為簡化示例使用單例;高併發環境建議使用 ThreadLocal 或 JDK 8+ DateTimeFormatterParsePosition(0) 避免拋出異常,返回 null 表示格式錯誤此工具類代碼簡潔、依賴最小、語義清晰,可直接集成到項目公共庫中。