zoukankan      html  css  js  c++  java
  • Java8 日期和时间API

    LocalDate、LocalTime、Instant、Duration、Period

    1.1使用LocalDate和LocalTime

    1.1.1LocalDate的创建方式和相关方法使用示例

     public void localDate() {
            LocalDate date = LocalDate.of(2019, 11, 1);
            int year = date.getYear();// 2019
            Month month = date.getMonth();// NOVEMBER
            int day = date.getDayOfMonth();// 1
            DayOfWeek dow = date.getDayOfWeek();// FRIDAY
            int len = date.lengthOfMonth();// 30
            boolean leap = date.isLeapYear();// false
            System.out.println(year + ", " + month + ", " + day + ", " + dow + ", " + len + ", " + leap);
    
            LocalDate date2 = LocalDate.now();
            int year2 = date2.get(ChronoField.YEAR);//2019
            int month2 = date2.get(ChronoField.MONTH_OF_YEAR);// 12
            int day2 = date2.get(ChronoField.DAY_OF_MONTH);// 14
            int dow2 = date2.get(ChronoField.DAY_OF_WEEK);//  6
            System.out.println(year2 + ", " + month2 + ", " + day2 + ", " + dow2);
            
            //不可以写成2019-11-1 会报DateTimeParseException
            LocalDate date3 = LocalDate.parse("2019-11-01");
            int year3 = date3.get(ChronoField.YEAR);//2019
            int month3 = date3.get(ChronoField.MONTH_OF_YEAR);// 11
            int day3 = date3.get(ChronoField.DAY_OF_MONTH);// 1
            int dow3 = date3.get(ChronoField.DAY_OF_WEEK);// 5
            System.out.println(year3 + ", " + month3 + ", " + day3 + ", " + dow3);
        }

    1.1.1LocalTime对象的创建方式以及相关方法示例

    @Test
        public void localTime() {
            LocalTime time = LocalTime.of(11, 06, 23);
            int hour = time.getHour();
            int minute = time.getMinute();
            int second = time.getSecond();
            System.out.println(hour + ":" + minute + ":" + second);//  11:6:23
    
            LocalTime time2 = LocalTime.now();
            int hour2 = time2.get(ChronoField.HOUR_OF_DAY);
            int minute2 = time2.get(ChronoField.MINUTE_OF_HOUR);
            int second2 = time2.get(ChronoField.SECOND_OF_MINUTE);
            System.out.println(hour2 + ":" + minute2 + ":" + second2);//当前时间
    
            // 写13:9:22会报错,DateTimeParseException异常,可以传一个DateTimeFormatter自定义格式
            LocalTime time3 = LocalTime.parse("13:09:22");
            int hour3 = time3.get(ChronoField.HOUR_OF_DAY);
            int minute3 = time3.get(ChronoField.MINUTE_OF_HOUR);
            int second3 = time3.get(ChronoField.SECOND_OF_MINUTE);
            System.out.println(hour3 + ":" + minute3 + ":" + second3);// 13:9:22
        }

    1.1.3LocalDateTime对象3种创建方式以及相关方法示例

     public void localDateTime() {
            LocalDate date = LocalDate.now();
            LocalTime time = LocalTime.now();
     
            // 创建LocalDateTime
            LocalDateTime dateTime = LocalDateTime.of(2019, 11, 1, 13, 32, 28);
            LocalDateTime dateTime2 = LocalDateTime.of(date, time);
            LocalDateTime dateTime3 = date.atTime(13, 32, 28);
            LocalDateTime dateTime4 = date.atTime(time);
            LocalDateTime dateTime6 = time.atDate(date);
     
            // 转化
            LocalDate date2 = dateTime2.toLocalDate();
            LocalTime time2 = dateTime2.toLocalTime();
        }

    1.1.4 机器的日期和时间格式

    你可以通过向静态工厂方法ofEpochSecond传递一个代表秒数的值创建一个该类的实例。静态工厂方法ofEpochSecond还有一个增强的重载版本,它接收第二个以纳秒为单位的参数值,对传入作为秒数的参数进行调整。重载的版本会调整纳秒参数,确保保存的纳秒分片在0到999 999999之间。这意味着下面这些对ofEpochSecond工厂方法的调用会返回几乎同样的Instant对象:

    Instant.ofEpochSecond(3); Instant.ofEpochSecond(3, 0); // 2 秒之后再加上100万纳秒(1秒) Instant.ofEpochSecond(2, 1_000_000_000); // 4秒之前的100万纳秒(1秒) Instant.ofEpochSecond(4, -1_000_000_000);

    正如你已经在LocalDate及其他为便于阅读而设计的日期-时间类中所看到的那样,Instant类也支持静态工厂方法now,它能够帮你获取当前时刻的时间戳。我们想要特别强调一点,Instant的设计初衷是为了便于机器使用。它包含的是由秒及纳秒所构成的数字。所以,它无法处理那些我们非常容易理解的时间单位。比如下面这段语句:

    int day = Instant.now().get(ChronoField.DAY_OF_MONTH);

    它会抛出下面这样的异常:

    Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth

    你可以通过Duration和Period类使用Instant

    1.1.5 定义Duration和Period(时间间隔对象)

    • Duration:可以传2个localTime对象,localDateTime对象或者Instant对象
    • Period:用年,月,日建模,可以传2个localDate对象
    Duration d1 = Duration.between(time1, time2);
    Duration d2 = Duration.between(dateTime1, dateTime2);
    Duration d3 = Duration.between(instant1, instant2);

    由 于LocalDateTime和Instant是为不同的目的而设计的,一个是为了便于人阅读使用,另一个是为了便于机器处理,所以你不能将二者混用。如果你试图在这两类对象之间创建duration,会触发一个DateTimeException异常 。 如果你需要以年、月或者日的方式对多个时间单位建模,可以使用Period类。使用该类的工厂方法between,你可以使用得到两个LocalDate之间的时长,如下所示 :

    Period period = Period.between(LocalDate.of(2019, 11, 07), LocalDate.of(2019, 11, 07));

    Duration和Period类都提供了很多非常方便的工厂类,直接创建对应的实例;换句话说,就像下面这段代码那样,不再是只能以两个temporal对象的差值的方式来定义它们的对象。

    Duration threeMinutes = Duration.ofMinutes(3); Duration fourMinutes = Duration.of(4, ChronoUnit.MINUTES); Period tenDay = Period.ofDays(10); Period threeWeeks = Period.ofWeeks(3); Period twoYearsSixMonthsOneDay = Period.of(2, 6, 1);

    1.2 操纵 解析和格式化日期

    1.2.1

    • 以比较直观的方式操纵LocalDate的属性

    下面的这段代码中所有的方法都返回一个修改了属性的对象。它们都不会修改原来的对象!

    LocalDate date1 = LocalDate.of(2019, 11, 1);//2019-11-01 LocalDate date2 = date1.withYear(2020);//2020-11-01 LocalDate date3 = date2.withDayOfMonth(25);//2020-11-25 LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 9);//2020-09-25
    • 以相对方式修改LocalDate的属性
    @Test public void editDateTime() { LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01 LocalDate date2 = date1.plusWeeks(1);// 2019-11-08 LocalDate date3 = date2.minusYears(2);// 2017-11-08 LocalDate date4 = date3.plus(6, ChronoUnit.MONTHS);// 2018-05-08 }

    1.2.3 TemporalAdjuster

    @Test public void adjust() { LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01 LocalDate date2 = date1.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));// 2019-11-03 LocalDate date3 = date2.with(TemporalAdjusters.lastDayOfMonth());// 2019-11-30 }

    TemporalAdjuster类的工厂方法

     1.2.4自定义格式化输出日期

    新版本,我们拥有一个线程安全的类:DateTimeFormatter 来看代码

    @Test
        public void formatPrint() {
            LocalDate date = LocalDate.of(2019, 11, 01);
            String s1 = date.format(DateTimeFormatter.BASIC_ISO_DATE);// 20191101
            String s2 = date.format(DateTimeFormatter.ISO_LOCAL_DATE);// 2019-11-01
    
            LocalDate date1 = LocalDate.parse("20191101", DateTimeFormatter.BASIC_ISO_DATE);
            LocalDate date2 = LocalDate.parse("2019-11-01", DateTimeFormatter.ISO_LOCAL_DATE);
    
            // 自定义格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            String formattedDate = date.format(formatter);
            System.out.println(formattedDate);// 01/11/2019
            LocalDate date3 = LocalDate.parse(formattedDate, formatter);
    
            // 带时区的日期(本地化)
            DateTimeFormatter italianFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.ITALIAN);
            String formattedDate2 = date.format(italianFormatter); 
            LocalDate date4 = LocalDate.parse(formattedDate2, italianFormatter);
        }
    故乡明
  • 相关阅读:
    pyecharts学习
    反爬
    pandas
    用 pymongo 操作 MongoDB 数据库
    数据库隔离级别---读未提交,读已提交,重复读,序列化
    vscode 配置c++和python编译和调试环境
    sublime Text3 配置c++编译环境并设置快捷键
    GIT学习笔记
    redis单节点部署
    二元多项式求逆中的小坑
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/14217478.html
Copyright © 2011-2022 走看看