1, String time conversion Date
The format passed by the user is "20201010", "2020-1010" or "2020.10.10". To convert to Date, use the DateUtil.parse() method in Hutool. parse() will automatically identify the string to obtain the Date type. Data, the date format obtained is 2020-10-10 type. In this way, there is no need to determine what type of time string the user enters.
Note: If the format of the string is 2020.02 and there is no complete date, DateUtil.parse() will not be able to recognize it, and you must add a format style after it.
String strTime = "2020.10.10";
// 输出2020-10-10 00:00:00
Date date = DateUtil.parse(strTime);
// 如果字符串时间不是完整格式,例如2020-10
String strTime = "2020-10";
// 输出 2020-10-01 00:00:00
Date date = DateUtil.parse(strTime,"yyyy-MM");
2. Convert Date type to string
Use the DateUtil tool class:
Date date = DateUtil.date();
// 年月日2020-12-24
System.out.println("年月日" + DateUtil.formatDate(date));
// 时分秒16:49:08
System.out.println("时分秒" + DateUtil.formatTime(date));
// 年月日 时分秒2020-12-24 16:49:08
System.out.println("年月日 时分秒" + DateUtil.formatDateTime(date));