續上篇,聚焦兩日期間隔計算、String/Date/Long 三向轉換、按年月周解析日期、星期判斷、Java 與 Oracle/SQL Server 日期類型映射、Date⇄Timestamp 轉換實用代碼。
public int getIntervalDays(Calendar start, Calendar end) {
if (start.after(end)) { Calendar t = start; start = end; end = t; }
long diff = end.getTimeInMillis() - start.getTimeInMillis();
return (int) (diff / (1000 * 60 * 60 * 24));
}
public int getIntervalDays(Date start, Date end) {
if (start.after(end)) { Date t = start; start = end; end = t; }
long diff = end.getTime() - start.getTime();
return (int) (diff / (1000 * 60 * 60 * 24));
}
public int getDaysBetween(Calendar d1, Calendar d2) {
if (d1.after(d2)) { Calendar t = d1; d1 = d2; d2 = t; }
int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
int y2 = d2.get(Calendar.YEAR);
if (d1.get(Calendar.YEAR) != y2) {
d1 = (Calendar) d1.clone();
do {
days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
d1.add(Calendar.YEAR, 1);
} while (d1.get(Calendar.YEAR) != y2);
}
return days;
}
應用場景:郵箱「三周內郵件」查詢 → 當前時間減 21 天得到閾值,轉 Long 比較高效。
// String → Date → Long
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy hh:mm:ss a", Locale.US);
Date d = sdf.parse("5/13/2003 10:31:37 AM");
long lv = d.getTime();
// Long → String
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = fmt.format(new Date(lv));
// "2003-05 5 星期五" → 日期
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM w E");
Date d = f1.parse("2003-05 5 星期五");
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(d));
// 判斷星期幾
SimpleDateFormat f2 = new SimpleDateFormat("E");
System.out.println(f2.format(new Date())); // 如 "週六"
| 數據庫類型 | Java 類型 | 說明 |
|---|---|---|
| Oracle DATE | java.sql.Date | 僅年月日 |
| SQL Server DATETIME | java.sql.Timestamp | 年月日時分秒毫秒 |
| MySQL DATETIME | java.sql.Timestamp / LocalDateTime | 推薦 Timestamp 或 Java 8 新類型 |
// 通用工具方法
public static java.sql.Timestamp string2Time(String s) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
df.setLenient(false);
return new java.sql.Timestamp(df.parse(s).getTime());
}
public static java.sql.Date string2Date(String s) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
df.setLenient(false);
return new java.sql.Date(df.parse(s).getTime());
}
// Date → Timestamp
Timestamp ts = new Timestamp(new Date().getTime());
// Timestamp → Date (自動截斷 nanos)
Date d = new Date(ts.getTime());
// 字符串雙向演示
String sDate = "2005-8-18";
String sTs = "2005-8-18 14:21:12.123";
System.out.println("Date: " + string2Date(sDate));
System.out.println("Timestamp: " + string2Time(sTs));
所有新代碼請直接使用 java.time.LocalDate、LocalDateTime、Instant、Duration、Period,配合 DateTimeFormatter 完成上述所有場景,徹底解決線程安全、時區、不可變性等歷史包袱。