制作一个工具类:DateUtil,进行日期和字符串之间的格式转换.
工具类:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static String dateString(Date date){//将日期转为字符串
date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss");
return sdf.format(date);
}
public static Date stringDate (String str){//将字符串转为日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//日期格式
str.matches("\\d{4}+\\d{2}+\\d{2}");
Date date = new Date();
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
测试类:
public class Test {
public static void main(String[] args) {
String str = "2021-11-26";
System.out.println(DateUtil.stringDate(str));
Date date = new Date();
System.out.println(DateUtil.dateString(date));
}
}
运行结果: