import java.util.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
//一般情況下使用SimpleDateFormat而不是DateFormat
String -> Date
//注意兩者格式匹配
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse("1987-05-04 12:34:23");
output: Mon May 04 12:34:23 CDT 1987
Date -> String
//可以設置任意的轉換格式
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateStr = df.format(new Date());
output: 2019/12/13 14:08:24
String -> Timestamp
//System.currentTimeMillis()比new Date()執行效率高
Timestamp ts = new Timestamp(System.currentTimeMillis());
ts = Timestamp.valueOf("1987-05-04 11:49:45");
output: 1987-05-04 11:49:45.0
Timestamp -> String
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsStr = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//方法一 (一般用此法,可以自由設置格式)
tsStr = sdf.format(ts);
//方法二
tsStr = ts.toString();
output: 2019-12-13 14:16:14
2019-12-13 14:16:14.282
Timestamp -> Date
Timestamp ts = new Timestamp(System.currentTimeMillis());
Date date = ts;
output: 2019-12-13 14:19:30.098
Date -> Timestamp
父類不可直接轉換成子類,可利用String實現
//有此種寫法
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
output: 2019-12-13 14:21:47.355