借用java.text.SimpleDateFormat類,實現Date類型和String的相互轉換
1. String轉java.util.Date
//sdf參數格式,必須與strDate格式相對應,否則拋出ParseException
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = "2020-04-13 20:27:02";
Date now = null;
try {
now = sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(now);//Mon Apr 13 20:27:02 CST 2020
2. Date轉需要的String格式
按照需要,填寫正確格式的參數,如yy表示輸出年份後兩位數字,yyyy則表示輸出4位年份數字
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = sdf.format(now);
System.out.println(result);// 2020-04-13 20:27:02
其他格式要求如下: