Date and time API in java 8

       In addition to the new features such as Lambda expressions and Stream streams, Java 8 also has new date and time APIs. Why do you introduce new date processing APIs? The old date processing class is not thread safe, and it is very troublesome to deal with time zones. Therefore, Java 8 has added a lot of new APIs under the java.time package, including Local (local, simplified date and time processing, no time zone issues) and Zoned (time zone, date and time are processed through the specified time zone).

How to use it, just give a few examples.

        //本地API
        LocalDateTime currentime = LocalDateTime.now();
        System.out.println("当前时间:"+currentime);
        LocalDate date1 = currentime.toLocalDate();
        System.out.println("当前日期的年月日:"+ date1);
        LocalTime time1 = currentime.toLocalTime();
        System.out.println("当前日期的时分秒:"+time1);
        LocalDateTime updateDate = currentime.withDayOfMonth(10).withMonth(9).withYear(2018);
        System.out.println("修改后的日期:"+updateDate);

        LocalDate date2 = LocalDate.of(2017,Month.DECEMBER,12);
        System.out.println("自定义一个日期:"+date2);

        LocalTime time2 = LocalTime.of(12,34,56);
        System.out.println("自定义时分秒:"+time2);

        LocalTime time3 = LocalTime.parse("10:23:45");
        System.out.println("字符串转换为时间:"+time3);

        //时区API
        ZonedDateTime zoneDate = ZonedDateTime.now();
        System.out.println("带有时区的日期:"+zoneDate);
        ZoneId id = ZoneId.systemDefault();
        System.out.println("获取默认时区:"+id);

        ZoneId updateId = ZoneId.of("Europe/Paris");
        System.out.println("自定义时区:"+updateId);

        结果:
        当前时间:2020-08-17T22:31:21.686
        当前日期的年月日:2020-08-17
        当前日期的时分秒:22:31:21.686
        修改后的日期:2018-09-10T22:31:21.686
        自定义一个日期:2017-12-12
        自定义时分秒:12:34:56
        字符串转换为时间:10:23:45
        带有时区的日期:2020-08-17T22:31:21.706+08:00[Asia/Shanghai]
        获取默认时区:Asia/Shanghai
        自定义时区:Europe/Paris

There are many other methods for dates, so I won’t give examples one by one. You can read the source code and learn by yourself.

Guess you like

Origin blog.csdn.net/wzs535131/article/details/108066430