当前位置: 代码迷 >> 综合 >> JDK8 时间
  详细解决方案

JDK8 时间

热度:39   发布时间:2023-11-22 11:02:52.0
       DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;LocalDateTime now = LocalDateTime.now();System.out.println(formatter.format(now));System.out.println(now);
输出: 2022-03-19T11:47:00.238
        DateTimeFormatter dateTime = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);System.out.println(dateTime.format(now));
输出: 2022年3月19日 上午11时47分00秒
        LocalDateTime today = LocalDateTime.now();DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formatDate = dtf.format(today);System.out.println(formatDate);
        LocalDateTime now = LocalDateTime.now();LocalDateTime old = LocalDateTime.of(2020, 1, 20, 15, 58, 0);Duration duration = Duration.between(old, now);

LocalDateTime 转 LocalDate

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();

LocalDate 转 LocalDateTime

LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime1 = localDate.atStartOfDay();
LocalDateTime localDateTime2 = localDate.atTime(8,20,33);
LocalDateTime localDateTime3 = localDate.atTime(LocalTime.now());

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);
//格式化LocalDateTime、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));

Date 转 LocalDateTime

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

LocalDate 转 Date

LocalDate localDate = LocalDate.now();
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());

Date 转 LocalDate

Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();

LocalDate获取时间戳

LocalDate.now().atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli()

LocalDateTime获取时间戳

LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();