LocalDateTime、LocalDate、Date 转为 String

上篇博客中,介绍了 LocalDateTime、LocalDate 及 Date 的相互转换,另外的场景就是需要把 LocalDateTime、LocalDate 或者是 Date与 String 字符串进行转换。

LocalDateTime、LocalDate、Date 转String

//Date转String
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateString = sdf.format(date);

//LocalDateTime转String
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String localDateTimeString = dtf1.format(localDateTime);

//LocalDate转String
LocalDate localDate = LocalDate.now();
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String localDateString = dtf2.format(localDate);

String 转 Date、LocalDateTime、LocalDate

//String转Date
String dateString = "2020-10-27 14:53:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(dateString);

//String转LocalDateTime
String localDateTimeString = "2020-10-27 18:15:00";
DateTimeFormatter dtf1 = ofPattern("yyyy-MM-dd hh:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(localDateTimeString, dtf1);

//String转LocalDate
String localDateString = "2020-10-27";
DateTimeFormatter dtf2 = ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(localDateString, dtf2);

相关文章:

  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
  • 2021-07-01
  • 2022-02-18
猜你喜欢
  • 2022-01-19
  • 2021-08-28
  • 2021-06-30
  • 2021-11-09
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案