1.阅读

1.1Instant

①获取当前时间Instant.now(),得到一个时间戳
②当前的时间戳加上或减取某个Duration

1.2Duration

可以计算两个时间间的差值,计算的结果是 秒+纳秒,分两个字段存储
因此纳秒存储的是说,相差了n秒零纳秒,所以int就可以存储纳秒

1.3Period

可以设置两日期的时间差

1.4ZonedTime ZonedDateTime

1.5LocalTime

1.6LocalDate

1.7LocalDateTime

本来是想整理好的,可是Java核心卷的东西实在看的头疼。我感觉在开发中用到最多的就是
LocalXXX 和 Instant /Period 和 Duration

2.场景练习

2.1Date和Instant和LocalDateTime的转换

Date—-> Instant

  1. Instant instant = Instant.ofEpochMilli(date.getTime());

Instant—>Date

  1. Date date1 = new Date(Instant.now().toEpochMilli());
  2. Date date2 =Date.from(instant)

Date—>LocalDateTime(Date -> Instant -> ZoneDateTime)

  1. LocalDateTime localDateTime1 = Instant.ofEpochMilli(date2.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();

LocalDateTime —>Date( LocalDateTime—> ZoneDatetime—> Instant—>Date)

  1. Instant instant1 = now.atZone(ZoneId.systemDefault()).toInstant();
  2. Date from1 = Date.from(instant1);

2.2常用操作

①LocalDateTime获取指定日期 00:00:00 和 23:59:59

  1. @Test
  2. public void testGetMaxAndMin()
  3. {
  4. LocalDateTime localDateTime = LocalDateTime.now();
  5. LocalDateTime minTime = LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MIN);
  6. System.out.println(minTime);
  7. LocalDateTime maxTime = LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX);
  8. System.out.println(maxTime);
  9. }

②计算A和B的LocalDateTime的相差天数(精确到秒)

  1. @Test
  2. public void testBetween() {
  3. LocalDateTime now = LocalDateTime.now();
  4. System.out.println(now);
  5. LocalDateTime localDateTime = now.plusDays(20);
  6. System.out.println(localDateTime);
  7. Duration between = Duration.between(now, localDateTime);
  8. long l = between.toDays();
  9. System.out.println(l);
  10. }