在 Java 中,日期(Date)與時間戳(timestamp,即自 1970-01-01 00:00:00 UTC 起的毫秒數)之間的轉換非常常見,例如與前端或第三方介面交換資料時。核心其實只有兩個動作:用 SimpleDateFormat 把字串解析成 Date,再用 Date.getTime() 取得毫秒值;反過來則是用 new Date(long) 建立物件,再格式化輸出。
/*
* 將時間字串轉換為時間戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/*
* 將時間戳轉換為時間字串
*/
public static String stampToDate(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}