Before JDK8, mutual conversion between multiple strings implemented using java.text.SimpleDateFormat
Time to String
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date()));
2020-03-16 23:57:36
String transfer time
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
System.out.println(format.parse("2010年4月23日 9时34分12秒"));
Fri Apr 23 09:34:12 CST 2010
After JDK8, often used java.time.format.DateTimeFormatter (exact match for high format)
Time to String
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(LocalDateTime.now().format(pattern));
2020-03-17 00:10:00
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(LocalDate.now().format(pattern));
2020-03-17
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(LocalTime.now().format(pattern));
00:12:04
Note: Time format must correspond with each other, or else there will be error
LocalDateTime.now () -> date, minutes and seconds
LocalDate.now () -> date
LocalTime.now () -> Minutes and seconds
String transfer time
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
System.out.println(LocalDateTime.parse("2010年04月23日 09时34分12秒", pattern));
2010-04-23T09: 34: 12
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
System.out.println(LocalDate.parse("2010年04月23日", pattern));
2010-04-23
ateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH时mm分ss秒");
System.out.println(LocalTime.parse("09时34分12秒", pattern));
09:34:12