当前位置: 代码迷 >> 综合 >> Date LocalDate LocalDateTime的转换使用
  详细解决方案

Date LocalDate LocalDateTime的转换使用

热度:11   发布时间:2024-02-04 23:36:15.0

最近项目经常使用到JDK1.8中LocalDate LocalDateTime的时间转换问题,记录一下:

Date 转 LocalDate

		Date date = new Date();Instant instant = date.toInstant(); // 时间戳ZoneId zoneId = ZoneId.systemDefault(); // 时区ZonedDateTime zonedDateTime = instant.atZone(zoneId); // 特定时区对应的日期时间LocalDate localDate = zonedDateTime.toLocalDate();date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate 转 Date

		LocalDate localDate = LocalDate.now();ZoneId zoneId = ZoneId.systemDefault();ZonedDateTime zdt = localDate.atStartOfDay(zoneId);Date date = Date.from(zdt.toInstant());补充LocalDate用到的一些方法:LocalDate firstLocalDate = localDate.with(TemporalAdjusters.firstDayOfMonth());// 获取月第一天LocalDate lastLocalDate = localDate.with(TemporalAdjusters.lastDayOfMonth());// 获取月最后一天long dateDiff = endLocalDate.toEpochDay() - startLocalDate.toEpochDay();// 获取两个日期相差天数localDate.minusDays(1);//日期减一天localDate.plusDays(1);//日期加一天

Date 转 LocalDateTime

		Date date = new Date();Instant instant = date.toInstant();ZoneId zoneId = ZoneId.systemDefault();LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

LocalDateTime 转 Date

		LocalDateTime localDateTime = LocalDateTime.now();ZoneId zoneId = ZoneId.systemDefault();ZonedDateTime zdt = localDateTime.atZone(zoneId);Date date = Date.from(zdt.toInstant());

LocalDate LocalDateTime 和字符串时间转换

		DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");LocalDate localDate = LocalDate.now();String localDateStr = localDate.format(dtf1);LocalDate localDate1 = LocalDate.parse("2020-07-20", dtf1);DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime localDateTime = LocalDateTime.now();String localDateTimeStr = localDateTime.format(dtf2);LocalDateTime localDateTime1 = localDateTime.parse("2020-07-20 20:30:00", dtf2);
  相关解决方案