1、String转Date
String str1 = "2021-09-24 12:13:14";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate1 = null;
try {
myDate1 = sdf1.parse(str1);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("myDate1: "+myDate1);
2、Date转String
Date myDate = new Date();
System.out.println("myDate:" + myDate + "\n");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String strDate1 = sdf1.format(myDate);
System.out.println("strDate1:" + strDate1);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String strDate2 = sdf2.format(myDate);
System.out.println("strDate2:" + strDate2);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate3 = sdf3.format(myDate);
System.out.println("strDate3:" + strDate3);
SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String strDate4 = sdf4.format(myDate);
System.out.println("strDate4:" + strDate4);