LocalDateTime、LocalDate、Date的相互转换及与String类型的相互转换
目录
前言:LocalDateTime 及 LocalDate 是 Java8 的新特性,有时为了兼容 Date 类型需要进行转换,以及与String之间的相互转换。
LocalDateTime 转 LocalDate:
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
LocalDateTime 转 Date
在LocalDateTime 转 Date 时,需要使用到 Java 8的几个类:
- ZoneId/ZoneOffset:表示时区
- ZonedDateTime: 表示特定时区的日期和时间
- Instant:表示时刻,不直接对应年月日信息,需要通过时区转换
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
Date date = Date.from(zonedDateTime.toInstant());
System.out.println("格式化前:localDateTime:" + localDateTime + " Date:" + date);
DateTimeFormatter localDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("格式化后:localDateTime:" + localDateTimeFormat.format(localDateTime)
+ " Date:" + dateFormat.format(date));
输出结果如下:
格式化前:localDateTime:2020-10-27T11:35:09.969 Date:Tue Oct 27 11:35:09 CST 2020
格式化后:localDateTime:2020-10-27 11:35:09 Date:2020-10-27 11:35:09
LocalDate 转 LocalDateTime
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime1 = localDate.atStartOfDay();
LocalDateTime localDateTime2 = localDate.atTime(8,8,8);
LocalDateTime localDateTime3 = localDate.atTime(LocalTime.now());
LocalDate 转 Date
LocalDate localDate = LocalDate.now();
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());
Date 转 LocalDateTime
Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = date.toInstant().atZone(zoneId).toLocalDateTime();
Date 转 LocalDate
Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();
LocalDateTime、LocalDate、Date 转String
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateString = sdf.format(date);
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String localDateTimeString = dtf1.format(localDateTime);
LocalDate localDate = LocalDate.now();
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String localDateString = dtf2.format(localDate);
String 转 Date、LocalDateTime、LocalDate
String dateString = "2021-9-22 08:08:08";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(dateString);
String localDateTimeString = "2021-9-22 08:08:08";
DateTimeFormatter dtf1 = ofPattern("yyyy-MM-dd hh:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(localDateTimeString, dtf1);
String localDateString = "2021-9-22";
DateTimeFormatter dtf2 = ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(localDateString, dtf2);
|