Java8 时间日期API

471 阅读3分钟

一、使用 LocalDate、LocalTime、LocalDateTime

  • LocalDateLocalTimeLocalDateTime 类的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。
     @Test
      public void localDateTimeTest() {
        // 获取当前时间日期
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now); // 2021-03-21T10:51:52.018324300
        // 设置指定时间日期,获得一个新的LocalDateTime
        LocalDateTime dateTime = LocalDateTime.of(2021, 3, 20, 23, 27, 0);
        System.out.println(dateTime);  // 2021-03-20T23:27
        // 修改LocalDateTime
        LocalDateTime plusYears = dateTime.plusYears(10);
        System.out.println(plusYears);  // 2031-03-20T23:27
        LocalDateTime plusMonths = dateTime.plusMonths(10);
        System.out.println(plusMonths);  // 2022-01-20T23:27
        LocalDateTime plusDays = dateTime.plusDays(10);
        System.out.println(plusDays);  // 2021-03-30T23:27
        LocalDateTime plusHours = dateTime.plusHours(10);
        System.out.println(plusHours);  // 2021-03-21T09:27
        LocalDateTime plusMinutes = dateTime.plusMinutes(10);
        System.out.println(plusMinutes);  // 2021-03-20T23:37
        LocalDateTime plusSeconds = dateTime.plusSeconds(10);
        System.out.println(plusSeconds);  // 2021-03-20T23:27:10
    
        LocalDateTime minusDays = dateTime.minusDays(10);
        System.out.println(minusDays);  // 2021-03-10T23:27
    
        LocalDateTime plus = dateTime.plus(Duration.ofDays(1));
        System.out.println(plus);  // 2021-03-21T23:27
    
        LocalDateTime withDayOfMonth = dateTime.withDayOfMonth(1);  // 修改为该月第一天
        System.out.println(withDayOfMonth);  // 2021-03-01T23:27
        LocalDateTime withDayOfYear = dateTime.withDayOfYear(1);  // 修改为该年第一天
        System.out.println(withDayOfYear);  // 2021-01-01T23:27
        LocalDateTime withMonth = dateTime.withMonth(1);  // 修改月份为1月,其余不变
        System.out.println(withMonth);  // 2021-01-20T23:27
        LocalDateTime withYear = dateTime.withYear(1);  // 修改年份
        System.out.println(withYear);  // 0001-03-20T23:27
        // 获取信息
        int dayOfMonth = dateTime.getDayOfMonth();  // 获取当前日期
        System.out.println(dayOfMonth);  // 20
        int dayOfYear = dateTime.getDayOfYear();  // 获取当前日是一年中的第几天
        System.out.println(dayOfYear);  // 79
        DayOfWeek dayOfWeek = dateTime.getDayOfWeek();  // 获取星期几
        System.out.println(dayOfWeek);  // SATURDAY
        Month month = dateTime.getMonth();  // 获取第几个月
        System.out.println(month);  // MARCH
        int monthValue = dateTime.getMonthValue();  // 获取第几个月的int值
        System.out.println(monthValue);    // 3
        int year = dateTime.getYear();  // 获取年份
        System.out.println(year);  // 2021
    
        // 比较日期
        boolean after = dateTime.isAfter(now);
        System.out.println(after);  // false
        boolean before = dateTime.isBefore(now);
        System.out.println(before);  // true
      }
    

    LocalTimeLocalDate同理

二、Instant 时间戳

  • 它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算
      @Test
      public void InstantTest() {
        Instant now = Instant.now();  // 按照标准的时间,不是当地的时间
        System.out.println(now);  // 2021-03-21T05:22:02.162907300Z
    
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);  // 2021-03-21T13:22:02.162907300+08:00
    
        long epochSecond = now.getEpochSecond();  // 从1970年开始,偏移了多少秒
        System.out.println(epochSecond);  // 1616304122
    
        Instant ofEpochSecond = Instant.ofEpochSecond(1);  // 从1970年开始,偏移一秒钟
        System.out.println(ofEpochSecond);  // 1970-01-01T00:00:01Z
      }
    

三、Duration 和 Period

  • Duration:用于计算两个“时间”间隔;Period:用于计算两个“日期”间隔
      @Test
      public void DurationTest() {
        Instant now = Instant.now();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        Instant now1 = Instant.now();
        // 计算时间差
        Duration duration = Duration.between(now, now1);
        System.out.println(duration);  // PT0.1126982S
    
        LocalDateTime now2 = LocalDateTime.now();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        LocalDateTime now3 = LocalDateTime.now();
        // 计算时间差
        Duration between = Duration.between(now2, now3);
        System.out.println(between);  // PT0.1067149S
    
        // 计算日期差
        Period between1 = Period.between(now2.toLocalDate(), now3.toLocalDate());
        System.out.println(between1);
    
        Period between2 = Period.between(LocalDate.of(2010, 10, 1), LocalDate.now());
        System.out.println(between2);
      }
    

四、日期的操纵

  • TemporalAdjuster : 时间校正器。有时我们可能需要获取。例如:将日期调整到“下个周日”等操作
  • TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现
      @Test
      public void temporalAdjusterTest() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nextDayOfWeekFRIDAY = now.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));  // 下周五
        System.out.println(nextDayOfWeekFRIDAY);
    
        LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());  // 这个月第一天
        System.out.println(firstDayOfMonth);
      }
    

五、解析与格式化

  • java.time.format.DateTimeFormatter 类:该类提供了三种格式化方法:
    • 预定义的标准格式
    • 语言环境相关的格式
    • 自定义的格式
      @Test
      public void DateTimeFormatterTest() {
        DateTimeFormatter isoWeekDate = DateTimeFormatter.ISO_LOCAL_DATE;  // 预定义的标准格式
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(isoWeekDate);  // 转换为String
        System.out.println(format);
    
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义格式化格式
        String format1 = now.format(formatter);  // 转换为String
        System.out.println(format1);
    
        LocalDateTime parse = LocalDateTime.parse("2020-01-01 10:10:10", formatter);  // 解析
        System.out.println(parse);
      }
    

六、时区的处理

  • Java8 中加入了对时区的支持,带时区的时间为分别为:ZonedDateZonedTimeZonedDateTime
  • 其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式例如 :Asia/Shanghai
  • ZoneId:该类中包含了所有的时区信息
    • getAvailableZoneIds() : 可以获取所有时区时区信息
    • of(id) : 用指定的时区信息获取 ZoneId 对象
      @Test
      public void ZoneIdTest() {
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        availableZoneIds.forEach(System.out::println);  // 获取所有时区
    
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println(now);  // 2021-03-21T13:17:21.184581100
        ZonedDateTime now1 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println(now1);  // 2021-03-21T13:17:21.184581100+08:00[Asia/Shanghai] 带上时区的本地时间
      }