···········································································································
1. 日期与字符串的相互转换:
public class TestDateRest {
public static void main(String[] args) throws ParseException {
String str1="2021-03-25 16:38:30";
String str2="2021-03-25";
String str3="2021/03/25";
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf3=new SimpleDateFormat("yyyy/MM/dd");
//先将字符转成日期
Date date1=sdf1.parse(str1);
Date date2=sdf2.parse(str2);
Date date3=sdf3.parse(str3);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
//再将日期转成字符串
String date4 = sdf1.format(date1);
String date5 = sdf2.format(date2);
String date6 = sdf3.format(date3);
System.out.println(date4);
System.out.println(date5);
System.out.println(date6);
}
}
输出结果:
Thu Mar 25 16:38:30 CST 2021
Thu Mar 25 00:00:00 CST 2021
Thu Mar 25 00:00:00 CST 2021
2021-03-25 16:38:30
2021-03-25
2021/03/25
总结:
***1、自定义格式是前提
***2、日期转字符串用format(),字符串转日期用parse()