zoukankan      html  css  js  c++  java
  • Java8(七) 新的DateTime API

    新的日期时间API

    1 日期/时间

    LocalDate:没有时区的日期

    LocalTime:没有时区的时间

    LocalDateTime:没有时区的日期时间

    ZonedDateTime:有时区的日期时间

    时区/ZoneId

    ZoneId.getAvailableZoneIds()获取所有可用的ZoneId。

    偏移量/ZoneOffset

    偏移量指的是偏移UTC时区的时分秒。

    如:+08:00的意思时超前于UTC八个小时,而 -05:45 意思是落后于UTC五小时四十五分钟。

    因为有着夏/冬令时的区分,所以偏移量会发生变化。

    获取日期时间信息
    LocalDateTime localDateTime = LocalDateTime.now();
    //很多,不一一写出来
    localDateTime.getXXX();
    
    日期时间调整
    • 加减
    LocalDateTime localDateTime = LocalDateTime.now();
    //很多,不一一写出来
    localDateTime.minusXXX();
    
    • 修改
    LocalDateTime localDateTime = LocalDateTime.now();
    //很多,不一一写出来
    localDateTime.withXXX();
    
    日期时间比较
    LocalDateTime time1 = LocalDateTime.now();
    LocalDateTime time2 = time1.minusDays(1);
    int compare = time1.compareTo(time2);
    boolean after = time1.isAfter(time2);
    boolean before = time1.isBefore(time2);
    boolean equal = time1.isEqual(time2);
    
    格式化
    LocalDateTime time = LocalDateTime.now();
    time.format(DateTimeFormatter.ofPattern("yyyyMM"));
    
    TemporalAdjuster
    LocalDateTime time = LocalDateTime.now();
    time.with(TemporalAdjusters.xxx());
    //dayOfWeekInMonth() – 一周中的某一天,例如,三月中第二个星期二
    //firstDayOfMonth() – 当前月的第一天
    //firstDayOfNextMonth() – 下一个月的第一天
    //firstDayOfNextYear() – 下一年的第一天
    //firstDayOfYear() – 当年的第一天
    //lastDayOfMonth() – 当月的最后一天
    //nextOrSame() – 下一次或当天发生的一周中的某天
    

    2 时间戳与时间段

    Instant

    时间戳。

    表示Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的时间。

    Instant instant = Instant.now();
    long epochSecond = instant.getEpochSecond();//秒数
    long l = instant.toEpochMilli();//毫秒数
    System.out.println(epochSecond);
    System.out.println(l);
    
    Period

    基于日期的时间段。

    LocalDate start = LocalDate.of(2020, 7, 28);
    LocalDate end = LocalDate.of(2020, 7, 29);
     
    Period period = Period.between(start, end);
    boolean negative = period.isNegative();//判断start end的大小
    System.out.println(period);//格式为P-1Y-1M-30D
    //基于年与日的时间段
    
    Duration

    基于时间的时间段。

    Instant start = Instant.parse("2020-07-09T06:07:30.00Z");
    Instant end = Instant.parse("2019-05-07T11:12:37.20Z");
    
    Duration duration = Duration.between(start, end);
    boolean negative = duration.isNegative();//判断start end的大小
    System.out.println(duration);//格式为PT-10290H-54M-52.8S
    //基于时分秒的时间段
    
  • 相关阅读:
    java、javaw和javaws的区别
    Hibernate4教程二:基本配置(2)
    Maven入门指南10:Maven的生命周期和插件
    Java中的断言(assert)
    MySQL的数据类型:文本、数字、日期/时间
    面向对象的三大基本特征和五大基本原则
    高内聚低耦合的介绍
    9.7 模拟赛
    16-17学期计划(每周)
    JZOJ 5281 钦点
  • 原文地址:https://www.cnblogs.com/lyldelove/p/13394909.html
Copyright © 2011-2022 走看看