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