美文网首页
JAVA8-时间Api

JAVA8-时间Api

作者: 一起来看雷阵雨 | 来源:发表于2018-11-08 18:57 被阅读0次

    Java中的时间api一直都备受诟病,十分的难用。
    比如:Date是可变的,DateFormatter的parse是非线程安全的,月份起点为0等等.
    为了解决这个问题,jdk8中新增了一套新的时间api,在java.time包下,以后再也不用去找第三方的额时间包了。
    其中最关键的几个类:LocalDate、LocalTime、LocalDateTime、Instant、Duration、Period
    下面一一解答

    1.LocalDate、LocalTime、LocalDateTime

    这三个类看名字就很容易理解其作用:

    • LocalDate只表示日期,不含时间信息。
    • LocalTime只表示时间,不含日期信息。
    • LocalDateTime则是同时包含时间和日期信息。
      在其中你可获取任何你想获取的相关信息,一年的第几个月,本月的第几个周等等。
      在此处还要再介绍一个接口:TemporalFiled,实现类:ChronoField。该接口定义了能够访问时间的属性,如:DayOfWeek等,简单实例:
            LocalDate date = LocalDate.now();
            LocalTime time = LocalTime.now();
            LocalDateTime localDateTime =
                    LocalDateTime.of(  //of列出所有的属性来构造对象
                            date.getYear(),
                            date.getMonthValue(),
                            date.get(ChronoField.DAY_OF_MONTH),
                            time.getHour(),
                            time.getMinute()
                    );
            int dayOfMonth = date.getDayOfMonth();  //直接获取dayOfMonth
            int dayOfMonth2 = date.get(ChronoField.DAY_OF_MONTH);  //根据ChronoField获取
    

    注意,并不是每个对象都支持ChronoFiled中的每一个属性,如:LocalTime只包含时间信息,肯定不能获取dayOfMonth这样的值,此时可以通过测试来确定:

    if (time.isSupported(ChronoField.NANO_OF_SECOND)){
        System.out.println(time.get(ChronoField.NANO_OF_SECOND));
    }
    

    2.Instant ——时间戳

    Instant表示一个明确的时间点,从1970年1月1日起所经过的秒数,主要方便机器使用!

    3.Duration和Period

    这两个类的作用也很容易从单词的意思中得出,代表一段持续时间,简单来说,就是两个时间点之间!

            Duration betweenTime = Duration.between(time,time.plusHours(3));
            Duration betwwenDateTime =     Duration.between(localDateTime,localDateTime.plusMonths(3));
            Duration threeHours = Duration.ofHours(3);
            
            Period betwwenDate = Period.between(date,date.plusMonths(3));
            Period threeWeek = Period.ofWeeks(3);
    

    注意:Duration不能用localDate,只能使用包含时间的LocalTime和LocalDateTime
    相同的,Period只能使用包含日期的LocalDate和LocalDateTime

    时间格式化

    相关文章

      网友评论

          本文标题:JAVA8-时间Api

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