美文网首页
java 8 日期时间API

java 8 日期时间API

作者: lvlvforever | 来源:发表于2018-11-19 23:06 被阅读12次

    java 8 之前的日期时间API实在太难用了,这也是joda-time的流行的直接原因。java 8 的新日期时间API设计的非常优雅好用。
    首先看下主要类。


    image.png

    直接上使用的例子。

    1 获取当前时间

    LocalTime localTime = LocalTime.now();
    System.err.println(localTime);
    输出
    22:05:11.878
    

    2 获取当前日期

    LocalDate date = LocalDate.now();
    System.err.println(date);
    输出
    2018-11-19
    

    3 获取当前日期时间

     LocalDateTime localDateTime =LocalDateTime.now();
     System.err.println(localDateTime);
    输出
    2018-11-19T22:10:03.141
    

    4 获取当前时间戳(unix timestamp)

    Instant instant = Instant.now();
    System.err.println(instant.toEpochMilli());
    输出当前距离1970-01-01 00:00:00 的毫秒数
    1542636689543
    

    5 将时间戳转换成日期时间

     Instant instant = Instant.ofEpochMilli(1542636689543L);
    // Instant.ofEpochSecond(1542636689L); 也可以传入秒数
     LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); 
     System.err.println(dateTime);
    

    instant是代表的是从1970-01-01 00:00:00开始的时间轴上的一个时间点,这个时间点根据不同的时区显示的日期时间不一样的。同一个时间戳1542636689543L,对于北京是2018-11-19T22:11:29.543,对于纽约则是2018-11-19T09:11:29.543。
    所以在将instant转成一个日期时间时,需要提供一个时区信息。如果不涉及多个时区,则使用ZoneId.systemDefault()即可。

    6 将日期时间转换成时间戳

     LocalDateTime localDateTime = LocalDateTime.now();
     System.err.println(localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
    输出
    1542637924476
    

    将日期时间转成时间戳时也需要提供一个时区。

    7 将日期时间格式化成字符串

    LocalDateTime localDateTime = LocalDateTime.now();
     String date = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
     System.err.println(date);
    输出
    2018-11-19 22:39:57
    
      LocalDate date = LocalDate.now();
      String d = date.format(DateTimeFormatter.ISO_DATE);
      System.err.println(d);
    输出
    2018-11-19 
    
     LocalTime time = LocalTime.now();
     String tim = time.format(DateTimeFormatter.ISO_TIME);
     System.err.println(tim);
    输出
    22:41:35.49
    

    LocalDateTime LocalDate LocalTime 都可以使用format方法将本身转换成可读性好的字符串。
    使用DateTimeFormatter进行格式化,这个类本身包含了一些常用的格式,也可以使用ofPattern方法自定义格式。

    8 将字符串转换成日期时间

          String time = "10:00:01";
            LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ISO_TIME);
            System.err.println("localTime=" + localTime);
    
            String date = "2018-11-19";
            LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);
            System.err.println("localDate=" + localDate);
    
            String dateTime = "2018-11-19 23:23:23";
            LocalDateTime localDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.err.println("localDateTime="+localDateTime);
    
    输出
    localTime=10:00:01
    localDate=2018-11-19
    localDateTime=2018-11-19T23:23:23
    
    

    日期和时间的处理非常类似,非常优雅。

    9 常用比较

           LocalDate localDate = LocalDate.now();
            LocalDate yesterday = LocalDate.parse("2018-11-18", DateTimeFormatter.ISO_DATE);
            System.err.println("今天在昨天之后:"+localDate.isAfter(yesterday)); // true
    
    

    基本上LocalDate LocalDateTime LocalTime 都有isAfter isBefore 等判断日期时间先后的方法。

    10 常用计算

     LocalDate localDate = LocalDate.now();
            System.err.println(localDate.plusDays(1));
            System.err.println(localDate.plusWeeks(1));
            LocalTime time = LocalTime.now();
            System.err.println(time.plusMinutes(1));
            LocalDateTime localDateTime = LocalDateTime.now();
            System.err.println(localDateTime.plusDays(1));
    输出
    2018-11-20
    2018-11-26
    23:05:04.694
    2018-11-20T23:04:04.694
    

    可以通过plusXXX方法对时间日期进行调整。当然有对应的minusXXX方法。

    11 计算两个日期时间直接的差值

            LocalDate curDate = LocalDate.now();
            LocalDate yesterday = LocalDate.parse("2018-11-19");
            Period period = Period.between(yesterday, curDate);
            System.err.println("相差天数:"+period.getDays());
    //流式运算
            curDate.plusMonths(1).plusHours(2).plusMonths(10);
    
            LocalTime curTime = LocalTime.now();
            LocalTime oldTime = LocalTime.parse("09:00:09");
            Duration duration = Duration.between(oldTime, curTime);
            System.err.println("相差秒数:" + duration.getSeconds());
            
    
    输出
    相差天数:1
    相差秒数:49461
    

    duration是计算时间的,period是计算日期的。

    12 带有时区的日期时间

    ZonedDateTime是带有时区的日期时间,是一种更适合用户阅读的格式

     ZonedDateTime dateTime = ZonedDateTime.now();
            System.err.println(dateTime);
    输出
    2018-11-20T23:00:44.250+08:00[Asia/Shanghai]
    

    OffsetDateTime同样是带有时区的日期时间,是一种面向机器的格式

     LocalDateTime dateTime = LocalDateTime.now();
            ZoneOffset offset = ZoneOffset.of("+08:00");
            OffsetDateTime offsetDateTime = OffsetDateTime.of(dateTime, offset);
            System.err.println(offsetDateTime);
    输出
    2018-11-20T23:03:47.170+08:00
    

    13 其他有用的类

    MonthDay 表示诸如生日的周期性事件

     LocalDate date = LocalDate.parse("2015-11-20");
            MonthDay monthDay = MonthDay.of(date.getMonth(), date.getDayOfMonth());
            MonthDay today = MonthDay.from(LocalDate.now());
            System.err.println(today.equals(monthDay)); //true
            System.err.println(monthDay);//--11-20
    

    YearMonth 表示诸如信用卡过期时间的周期性事件

    YearMonth yearMonth = YearMonth.from(LocalDate.now());
    System.err.println(yearMonth); //2018-11
    

    判断是否是闰年

     System.err.println(LocalDate.now().isLeapYear());
    

    14 和java.util.Date之间的转换

    java.util.Date添加了两个方法,toInstant()和fromInstant()。Date是带有时区的,默认是系统时区。
    Instant是不带时区的,所以在通过instant转换时记得注意时区。

    System.err.println(new Date().toInstant());
            Instant instant = new Date().toInstant();
            LocalDateTime time = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            System.err.println(time);
            System.err.println(new Date());
     Date date1 = Date.from(instant);
            System.err.println(date1);
    输出
    2018-11-20T15:21:17.867Z   不带时区
    2018-11-20T23:21:17.867 带上时区后显示是对的
    Tue Nov 20 23:21:17 CST 2018 Date本身带有时区
    Tue Nov 20 23:21:17 CST 2018
    

    LocalDateTime LocalDate LocalTime 与Date之间转换的桥梁就是Instant。

    目前接触到的有关于java 8的新日期时间API目前就这些,以后会逐渐更新。

    相关文章

      网友评论

          本文标题:java 8 日期时间API

          本文链接:https://www.haomeiwen.com/subject/umrzfqtx.html