• 70-Java的日期时间:Date、SimpleDateFormat、Calendar、JDK8后新增日期API


    本章学习介绍

    1、常用API

    2、Lambda

    3、常见算法


    需要学会什么?

    • 1、如何处理时间?
      • 在程序中经常需要处理时间,获取时间,时间判断,运算等。
    • 2、认识包装类?
      • Java认为一切皆对象,8种基本类型不是,如何实现的,集合、泛型也不支持基本类型,怎么解决?
    • 3、正则表达式?
      • 在程序中需要对各种信息进行格式合法性的校验,如手机号码、邮箱、身份证等等。
    • 4、经常需要操作数组元素?
      • 如何快捷操作数组元素,如输出数组内容、排序、元素搜索等。排序和搜索算法是啥样的?
    • 5、Lambda表达式?
      • 匿名内部类的代码是可以进一步的简化的,什么情况下可以简化,需要用什么知识完成?



    一、日期与时间

    1、Date类

    (1)Date类是啥?
    • Date类的对象在Java中代表的是当前所在系统的此刻的日期时间。

    (2)Date的构造器
    构造器名称说明
    public Date()创建一个Date对象,代表的是系统当前此刻日期时间。

    (3)Date的常用方法
    名称说明
    public long getTime()获取时间对象的毫秒值

    (4)Date类记录时间的2种形式
    • 形式1:

      • 日期对象
        在这里插入图片描述


        在这里插入图片描述


    • 形式2:

      • 指的是从1970年1月1日 00:00:00 走到此刻的总的毫秒数,应该是很大的。
        在这里插入图片描述


        在这里插入图片描述



    (5)时间毫秒值转换为日期对象

    时间毫秒值—>日期对象

    构造器说明
    public Date(long time)把时间毫秒值转换成Date日期对象

    Date方法说明
    public void setTime(long time)设置日期对象的时间为当前时间毫秒值对应的时间

    案例:
    • 请计算出当前时间往后走1小时121秒之后的时间是多少?
      在这里插入图片描述


      在这里插入图片描述


    总结

    1、日期对象如何创建,如何获取时间毫秒值?

    • 创建日期对象:
      • Date d = new Date();
    • 获取时间毫秒值:
      • 方式1: long time1 = d.getTime();
      • 方式2: long time2 = System.currentTimeMillis();

    2、时间毫秒值如何转成日期对象?

    • 时间毫秒值—>日期对象:
      • 方式1: Date d1 = new Date(timeMillis);
      • 方式2:
        • Date d2 = new Date();
        • d2.setTime(timeMillis);



    2、SimpleDateFormat

    (1)SimpleDateFormat是啥?
    • 可以对Date对象日期时间毫秒值 格式化 成我们喜欢的时间形式;

    • 也可以把字符串的时间形式 解析 成日期对象。
      在这里插入图片描述


    在这里插入图片描述


    在这里插入图片描述


    在这里插入图片描述


    在这里插入图片描述


    (2)SimpleDateFormat的构造器和格式化方法
    构造器说明
    public SimpleDateFormat()构造一个SimpleDateFormat,使用默认格式
    public SimpleDateFormat(String pattern)构造一个SimpleDateFormat,使用指定的格式

    方法说明
    public final String format(Date date)将日期格式化成:日期/时间字符串
    public final String format(Object time)将时间毫秒值格式化成:日期/时间字符串

    (3)格式化的常用的时间形式

    在这里插入图片描述


    package com.app.d2_simpledateformat;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
        目标:SimpleDateFormat 简单日期格式化类的使用
        1、格式化时间对象
        2、格式化时间毫秒值
     */
    public class SimpleDateFormatDemo1 {
        public static void main(String[] args) {
            // 1、获取当前日期时间
            Date date = new Date();
            System.out.println("未格式化的形式:" + date);
    
            // 2、格式化当前日期时间 (指定最终格式化的形式)
            /*
                请严格按照规范来格式化时间:
                yyyy——>年;MM——>月;dd——>日;HH——>时;mm——>分;ss——>秒;EEE——>周次;a——>上午/下午
             */
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月");
    
    
            // 3、格式化日期对象成自己指定的形式
            String time1 = sdf1.format(date);
            String time2 = sdf2.format(date);
            String time3 = sdf3.format(date);
            System.out.println("格式化后的形式1:" + time1);
            System.out.println("格式化后的形式2:" + time2);
            System.out.println("格式化后的形式3:" + time3);
    
            System.out.println("--------------------------------------");
    
            // 4、格式化时间毫秒值
            // 需求:请问121秒后的时间是多少?
            long timeMillis = System.currentTimeMillis() + 121 * 1000;   // 当前时间毫秒值 + 121 * 1000
            String newTime = sdf1.format(timeMillis);
            System.out.println("121秒后的时间是:" + newTime);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    未格式化的形式:Tue Aug 02 09:46:27 CST 2022
    格式化后的形式1:2022年08月02日 09:46:27 周二 上午
    格式化后的形式2:2022-08-02 09:46
    格式化后的形式3:2022年08月
    --------------------------------------
    121秒后的时间是:2022年08月02日 09:48:28 周二 上午
    
    Process finished with exit code 0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8


    (4)SimpleDateFormat解析字符串时间成为日期对象
    方法说明
    public Date parse(String source)从给定的字符串开始解析文本以生成日期
    案例
    • 需求:

      • 请计算出 2021年08月06日11点11分11秒,往后走2天14小时49分06秒后的时间是多少?
      package com.app.d2_simpledateformat;
      
      
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      
      /**
          目标:学会使用SimpleDateFormat解析字符串时间成为日期对象。
       */
      public class SimpleDateFormatTest2 {
          public static void main(String[] args) throws ParseException {
      //         需求:请计算出 2021年08月06日11点11分11秒,往后走2天14小时49分06秒后的时间是多少?
      
      //         1、定义字符串变量,记录时间:2021年08月06日 11:11:11
              String dateStr = "2021年08月06日 11:11:11";
      
      
      //         2、解析字符串时间成为日期对象(重点)。形式必须与被解析的形式完全吻合,否则运行时解析会报错!
              //                                                  2021年08月06日 11:11:11
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
              Date date = sdf.parse(dateStr);
      
              // 格式化输出一下2天14小时49分06秒前的时间
              String oldDate = sdf.format(date);
              System.out.println("2天14小时49分06秒前的时间是:" + oldDate);
      
      
      //         3、将解析后的日期对象转换成毫秒值,并计算2天14小时49分06秒后的时间是多少?
              // 计算方式:
              // 2天 == 2*24*60*60;14小时 == 14*60*60;49分 == 49*60;6秒 == 6
              // 2天14小时49分06秒 == (2*24*60*60 + 14*60*60 + 49*60 + 6) * 1000
              // 这里 2后面加个L,是因为如果以int类型进行运算,数据有可能会失真,所以要以long类型进行运算
              long timeMillis = date.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;
      
      
      //         4、将计算后的时间毫秒值转成日期对象
              // 格式化输出一下2天14小时49分06秒后的时间
              String newTime = sdf.format(timeMillis);
              System.out.println("2天14小时49分06秒后的时间是:" + newTime);
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42

    ****在这里插入图片描述


    在这里插入图片描述



    总结

    1、SimpleDateFormat可以格式化哪些时间形式?

    • 可以格式化日期对象,也可以格式化时间毫秒值
      在这里插入图片描述

    2、SimpleDateFormat如何进行字符串时间的解析的?

    • 调用SimpleDateFormat的parse方法
      在这里插入图片描述
      在这里插入图片描述





    3、日期时间案例练习:秒杀活动

    在这里插入图片描述

    • 需求:

      • 小贾下单并付款的时间为:2020年11月11日 0:03:47

      • 小皮下单并付款的时间为:2020年11月11日 0:10:11

      • 用程序说明这两位同学有没有参加上秒杀活动。

    • 分析实现:

      • 1、定义字符串变量,分别记录秒杀活动开始和结束的时间;
      • 2、定义字符串变量,分别记录小贾和小皮的下单并付款的时间;
      • 3、分别将这些时间解析成日期对象,再转换成毫秒值;
      • 4、判断:当小贾下单时间 在活动开始时间之后 与 活动开始时间之前,说明小贾秒杀成功!!否则小贾秒杀失败!!
      • 5、判断:当小皮下单时间 在活动开始时间之后 与 活动开始时间之前,说明小皮秒杀成功!!否则小皮秒杀失败!!
      package com.app.d2_simpledateformat;
      
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      
      /**
          案例:秒杀活动
          需求:
              秒杀活动开始时间:2020年11月11日 00:00:00
              秒杀活动结束时间:2020年11月11日 00:10:00
              1、小贾下单并付款的时间:2020年11月11日 00:03:47
              2、小皮下单并付款的时间:2020年11月11日 00:10:11
              用程序说明这俩同学有没有参加上秒杀活动?
       */
      public class SimpleDateFormatTest3 {
          public static void main(String[] args) throws ParseException {
              // 1、定义字符串变量,分别记录秒杀活动开始和结束的时间;
              String startDate = "2020年11月11日 00:00:00";
              String endDate = "2020年11月11日 00:10:00";
      
              // 2、定义字符串变量,分别记录小贾和小皮的下单并付款的时间;
              String xjDate = "2020年11月11日 00:03:47";
              String xpDate = "2020年11月11日 00:10:11";
      
              // 3、分别将这些时间解析成日期对象
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
              Date startTime = sdf.parse(startDate);    // 活动开始时间的日期对象
              Date endTime = sdf.parse(endDate);        // 活动结束时间的日期对象
              Date xjTime = sdf.parse(xjDate);          // 小贾下单时间的日期对象
              Date xpTime = sdf.parse(xpDate);          // 小皮下单时间的日期对象
      
              // 4、判断:当小贾下单时间 在活动开始时间之后 与 活动开始时间之前,说明小贾秒杀成功!!
              if (xjTime.after(startTime) && xjTime.before(endTime)) {
                  System.out.println("小贾恭喜你!!秒杀成功^_^ 开始发货啦~~");
              }else {
                  // 否则小贾秒杀失败!!
                  System.out.println("小贾很遗憾!时间到了!秒杀失败~~");
              }
      
              // 5、判断:当小皮下单时间 在活动开始时间之后 与 活动开始时间之前,说明小皮秒杀成功!!
              if (xpTime.after(startTime) && xpTime.before(endTime)) {
                  System.out.println("小皮恭喜你!!秒杀成功^_^ 开始发货啦~~");
              }else {
                  // 否则小皮秒杀失败!!
                  System.out.println("小皮很遗憾!时间到了!秒杀失败~~");
              }
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      小贾恭喜你!!秒杀成功^_^ 开始发货啦~~
      小皮很遗憾!时间到了!秒杀失败~~
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4

      • 这两个API是Date类的,Api文档可以找到,作用就是判断当前日期是否在此日期之后和之前:
        在这里插入图片描述



    4、Calendar

    (1)Calendar是啥?
    • Calendar:系统此刻日期对应的日历对象。

    • Calendar是一个抽象类,不能直接创建对象。
      在这里插入图片描述


    (2)获取Calendar对象
    • 这不是刚说完Calendar是抽象类吗?咋又能获取对象了呢?
      在这里插入图片描述



    • 所以,获取Calendar对象:

      Calendar rightNow = Calendar.getInstance();
      
      • 1
    • 和我们之前说的单例模式是一样的,这个 getInstance 也是在方法在内部创建一个对象返回的


    Calendar日历类创建日历对象的方法:

    方法说明
    public static Calendar getInstance()获取当前日历对象

    (3)Calendar常用方法
    方法说明
    public int get(int field)取日历中的某个字段信息。
    public void set(int field, int value)修改日历的某个字段信息。
    public void add(int field, int amount)为某个字段增加/减少指定的值。
    public final Date getTime()拿到此刻日期对象。
    public long getTimeMillis()拿到此刻时间毫秒值。

    package com.app.d3_Calendar;
    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    /**
        目标:学会使用Calendar类处理日期时间
     */
    public class CalendarDemo1 {
        public static void main(String[] args) {
            // 1、拿到系统此刻日历对象
            Calendar cal = Calendar.getInstance();
    
            Date date = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = sdf.format(date);
            System.out.println(time);
    
            // 2、获取日历的信息
            int year = cal.get(Calendar.YEAR);  // 年
            System.out.println(year + "年");
    
            int mm = cal.get(Calendar.MONTH) + 1;   // 月: 因为是从0开始数的,所以 +1
            System.out.println(mm + "月");
    
            int days = cal.get(Calendar.DAY_OF_YEAR);   // 一年中的第几天
            System.out.println("现在是一年中的" + days);
    
    
            // 3、修改日历的某个字段信息
            // cal.set(Calendar.HOUR, 12);      // 修改日历小时为 12 点
            // System.out.println(cal);
    
            // 4、为某个字段增加/减少指定的值
            // 请问64天后是什么时间?
            cal.add(Calendar.DAY_OF_YEAR, 64);  // 加64天
            cal.add(Calendar.MINUTE, 55);       // 加55分
    
            // 5、拿到此刻日期对象
            Date date2 = cal.getTime();
            String time2 = sdf.format(date2);
            System.out.println(time2);
    
            int days2 = cal.get(Calendar.DAY_OF_YEAR);   // 一年中的第几天
            System.out.println("现在是一年中的" + days2);
    
            // 6、拿到此刻时间毫秒值
            long timeMillis = cal.getTimeInMillis();
            System.out.println(timeMillis);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    2022-08-02 14:45
    2022年
    8月
    现在是一年中的214
    2022-10-05 15:40
    现在是一年中的278
    1664955641234
    
    Process finished with exit code 0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (4)注意:
    • Calendar是可变日期对象,一旦修改后起对象本身表示的时间将产生变化。

    总结

    1、Calendar如何去得到日历对象?

    • Calendar c = Calendar.getInstance();



    二、JDK8新增日期类

    (1)概述
    • 从JDK8开始,java.time包提供了新的日期和时间API,主要涉及的类型有:
      • LocalDate:不包含具体时间的日期。
      • LocalTime:不含日期的时间。
      • LocalDateTime:包含了日期及时间。
      • Instant:代表的是时间戳。
      • DateTimeFormatter:用于做时间的格式化和解析的。
      • Duration:用于计算两个 “时间” 间隔。
      • Period:用于计算两个 “日期” 间隔。
    • 新增的API严格区分了时刻、本地日期、本地时间,并且,对日期和时间进行运算更加方便
    • 其次,新API的类型几乎全部是不变类型(和String的使用类似),可以放心使用不必担心被修改

    (2)LocalDate、LocalTime、LocalDateTime
    • 他们分别表示:日期、时间、日期时间对象,他们的类的实例是不可变对象。
    • 他们三者构建对象和API都是通用的。

    构建对象的方式如下:

    方法说明
    public static Xxxx now();静态方法,根据当前时间创建对象LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();
    public static Xxxx of(…);静态方法,指定日期/时间创建对象LocalDate localDate1 = LocalDate.of(2020, 11, 11);
    LocalTime localTime1 = LocalTime.of(11, 11, 11);
    LocalDateTime localDateTime1 = LocalDateTime.of(2022, 8, 3, 15, 04, 33);

    • LocalDate

      package com.app.d4_jdk8_time;
      
      import java.time.LocalDate;
      import java.time.Month;
      
      public class Demo01LocalDate {
          public static void main(String[] args) {
              // 1、获取本地日期对象
              LocalDate nowDate = LocalDate.now();
              System.out.println("今天的日期:" + nowDate);
      
              // 2、获取本地日期的年、月、日
              int year = nowDate.getYear();           // 年
              int month = nowDate.getMonthValue();    // 月
              int day = nowDate.getDayOfMonth();      // 日
              System.out.println(year + "年" + month + "月" + day + "日");
      
              // 3、获取本地日期中当年的第几天
              int dayOfYear = nowDate.getDayOfYear();
              System.out.println("现在是一年中的第" + dayOfYear + "天");
      
              // 4、获取本地日期的星期(周次)
              System.out.println(nowDate.getDayOfWeek());             // 英文的星期(周次)
              int getWeekValue = nowDate.getDayOfWeek().getValue();   // 周次的值
      
              // 5、获取本地日期的月份
              System.out.println(nowDate.getMonth());             // 英文的月份
              System.out.println(nowDate.getMonth().getValue());  // 月份的值
      
              System.out.println("----------------------------------");
      
              // 6、直接传入对应的年月日
              LocalDate bt = LocalDate.of(2323, 11, 17);
              System.out.println(bt);
              // 还可以用枚举的方式选择
              System.out.println(LocalDate.of(2323, Month.NOVEMBER, 17));
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      今天的日期:2022-08-02
      2022年8月2日
      现在是一年中的第214天
      TUESDAY
      AUGUST
      8
      ----------------------------------
      2323-11-17
      2323-11-17
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11


    • LocalTime

      package com.app.d4_jdk8_time;
      
      import java.time.LocalTime;
      
      public class Demo02LocalTime {
          public static void main(String[] args) {
              // 1、获取本地时间对象
              LocalTime nowTime = LocalTime.now();
              System.out.println("今天的时间:" + nowTime);
      
              // 2、获取本地时间的时分秒
              int hour = nowTime.getHour();       // 时
              int minute = nowTime.getMinute();   // 分
              int second = nowTime.getSecond();   // 秒
              System.out.println(hour + ":" + minute + ":" + second);
      
              int nano = nowTime.getNano();   // 纳秒
              System.out.println("纳秒: " + nano);
      
              System.out.println("--------------------");
              // 3、直接传入对应的时间
              System.out.println(LocalTime.of(15, 34));   // 时分
              System.out.println(LocalTime.of(15, 34, 55));   // 时分秒
              System.out.println(LocalTime.of(15, 5, 34, 566));   // 时分秒纳秒
              LocalTime mTime = LocalTime.of(15, 5, 34, 566);
              System.out.println(mTime);
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      今天的时间:18:42:57.334265300
      18:42:57
      纳秒: 334265300
      --------------------
      15:34
      15:34:55
      15:05:34.000000566
      15:05:34.000000566
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10


    (3)LocalDateTime转换相关的API

    在这里插入图片描述

    • LocalDateTime的转换API

      方法说明
      public LocalDate toLocalDate()转换成一个LocalDate对象
      public LocalTime toLocalTime()转换成一个LocalTime对象
      package com.app.d4_jdk8_time;
      
      import java.time.LocalDate;
      import java.time.LocalDateTime;
      import java.time.LocalTime;
      
      /**
          LocalDateTime兼容了LocalDate和LocalTime,因此可以使用它们的API
       */
      public class Demo03LocalDateTime {
          public static void main(String[] args) {
              // 1、获取本地的日期时间
              LocalDateTime nowDateTime = LocalDateTime.now();
              System.out.println("今天是:" + nowDateTime);
      
              // 2、获取本地日期时间的年、月、日、时、分、秒、纳秒
              System.out.println(nowDateTime.getYear() + "年");          // 年
              System.out.println(nowDateTime.getMonthValue() + "月");    // 月
              System.out.println(nowDateTime.getDayOfMonth() + "日");    // 日
              System.out.println(nowDateTime.getHour() + "点");          // 时
              System.out.println(nowDateTime.getMinute() + "分");        // 分
              System.out.println(nowDateTime.getSecond() + "秒");        // 秒
              System.out.println(nowDateTime.getNano() + "纳秒");          // 纳秒
      
              // 3、获取当年的第几天
              System.out.println("今天是今年的第" + nowDateTime.getDayOfYear() + "天");
      
              // 4、获取星期——>周次
              System.out.println(nowDateTime.getDayOfWeek());     // 英文的周次
              System.out.println(nowDateTime.getDayOfWeek().getValue());  // 周次的值
      
              // 5、获取月份
              System.out.println(nowDateTime.getMonth());     // 英文的月份
              System.out.println(nowDateTime.getMonth().getValue());  // 月份的值
      
              // 6、LocalDateTime 可以转换为 LocalDate
              LocalDate ld = nowDateTime.toLocalDate();   // 年月日
              System.out.println(ld);
      
              // 7、LocalDateTime 可以转换为 LocalTime
              LocalTime lt = nowDateTime.toLocalTime();   // 时分秒纳秒
              System.out.println(lt);
              System.out.println(lt.getHour());   // 时
              System.out.println(lt.getMinute()); // 分
              System.out.println(lt.getSecond()); // 秒
              System.out.println(lt.getNano());   // 纳秒
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      今天是:2022-08-02T18:43:54.119622700
      2022年
      8月
      2日
      18点
      43分
      54秒
      119622700纳秒
      今天是今年的第214天
      TUESDAY
      2
      AUGUST
      8
      2022-08-02
      18:43:54.119622700
      18
      43
      54
      119622700
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21


    (4)修改相关的API
    • LocalDateTime 综合了 LocalDate、LocalTime里面的方法,所以下面只用 LocalDate、LocalTime 来举例。

    • 这些方法返回的是一个新的实例引用,因为LocalDateTime、LocalDate、LocalTime 都是不可变的。

      方法说明
      plusDays, plusWeeks, plusMonths, plusYears向当前 LocalDate 对象添加:几天、几周、几月、几年
      minusDays, minusWeeks, minusMonths, minusYears从当前 LocalDate 对象减去:几天、几周、几月、几年
      withDayOfMonth, withDayYear, withMonth, withYear将月份天数、年份天数、月份、年份修改为指定的值并返回新的LocalDate对象
      isBefore, isAfter比较两个LocalDate

      package com.app.d4_jdk8_time;
      
      import java.time.LocalDate;
      import java.time.LocalTime;
      import java.time.MonthDay;
      
      /**
          修改相关的API
       */
      public class Demo04UpdateTime {
          public static void main(String[] args) {
              // 1、获取当前时间
              LocalTime nowTime = LocalTime.now();
              System.out.println("今天的时间:");
              System.out.println(nowTime + "\n");
      
              // 2、从当前时间减去:1时、1分、1秒、1纳秒
              System.out.println(nowTime.minusHours(1));          // 1小时前
              System.out.println(nowTime.minusMinutes(1));      // 1分钟前
              System.out.println(nowTime.minusSeconds(1));      // 1秒钟前
              System.out.println(nowTime.minusNanos(1));         // 1纳秒前
      
              System.out.println("-----------------------------");
              // 3、向当前时间加上:1时、1分、1秒、1纳秒
              System.out.println(nowTime.plusHours(1));            // 1小时后
              System.out.println(nowTime.plusMinutes(1));        // 1分钟后
              System.out.println(nowTime.plusSeconds(1));        // 1秒钟后
              System.out.println(nowTime.plusNanos(1));           // 1纳秒后
      
              System.out.println("-----------------------------");
              // 不可变对象,每次修改都会产生新对象,因此nowTime还是不变
              System.out.println(nowTime);
      
              System.out.println("-----------------------------");
              // 我的日期
              LocalDate myDate = LocalDate.of(2019, 9, 2);
              // 今天的日期
              LocalDate nowDate = LocalDate.now();
      
              // 判断日期
              System.out.println("今天是2019年9月2日吗?" + myDate.equals(nowDate));
              System.out.println(myDate + "是在" + nowDate + "之前吗?" + myDate.isBefore(nowDate));
              System.out.println(myDate + "是在" + nowDate + "之后吗?" + myDate.isAfter(nowDate));
      
              System.out.println("-----------------------------");
              // 判断今天是不是你的生日
              // a、得到你的出生日期
              LocalDate myDate2 = LocalDate.of(2001, 8, 2);
              // b、得到当前日期
              LocalDate nowDate2 = LocalDate.now();
      
              // c、取出你的出生月、日,因为生日不需要判断年份
              MonthDay myMd = MonthDay.of(myDate2.getMonthValue(), myDate2.getDayOfMonth());
              // MonthDay myMd = MonthDay.from(myDate2);  // 取出月、日
      
              // d、取出当前月、日
              MonthDay nowMd = MonthDay.from(nowDate2);
      
              // e、今天是你的生日吗?
              System.out.println("今天是你的生日吗?" + myMd.equals(nowMd));
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      今天的时间:
      18:46:22.083825800
      
      17:46:22.083825800
      18:45:22.083825800
      18:46:21.083825800
      18:46:22.083825799
      -----------------------------
      19:46:22.083825800
      18:47:22.083825800
      18:46:23.083825800
      18:46:22.083825801
      -----------------------------
      18:46:22.083825800
      -----------------------------
      今天是2019年9月2日吗?false
      2019-09-02是在2022-08-02之前吗?true
      2019-09-02是在2022-08-02之后吗?false
      -----------------------------
      今天是你的生日吗?true
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22


    (5)Instant时间戳
    • JDK8获取时间戳特别简单,且功能更丰富。Instant类 由一个静态的工厂方法 now() 可以返回当前时间戳。

      Instant instant = Instant.now();
      System.out.println("当前时间戳是:" + instant);
      
      Date date = Date.from(instant);
      System.out.println("当前时间戳是:" + date);
      
      instant = date.toInstant();
      System.out.println(instant);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    • 时间戳是 包含日期和时间 的,与 java.util.Date 很类似,事实上 Instant 就是类似 JDK8以前的Date

    • InstantDate 两个类可以进行转换

      package com.app.d4_jdk8_time;
      
      import java.time.Instant;
      import java.time.ZoneId;
      import java.time.ZonedDateTime;
      import java.util.Date;
      
      public class Demo05Instant {
          public static void main(String[] args) {
              // 1、获取一个Instant时间戳对象
              Instant instant = Instant.now();
              System.out.println(instant);    // 全球统一的时间:世界标准钟
      
              // 2、获取一个系统此刻的时间戳:北京时间
              // a、先得到世界标准时间戳
              Instant instant2 = Instant.now();
              // b、将时区调成系统默认:因为我们的系统是中国的,所以就是北京时间
              ZonedDateTime zonedDateTime = instant2.atZone(ZoneId.systemDefault());
              System.out.println(zonedDateTime);
      
              // 3、如何去返回Date对象
              Date date = Date.from(instant);
              System.out.println(date);
      
              // 4、再转回Instant对象
              Instant it = date.toInstant();
              System.out.println(it);
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      2022-08-02T10:46:43.511785200Z
      2022-08-02T18:46:43.516772+08:00[Asia/Shanghai]
      Tue Aug 02 18:46:43 CST 2022
      2022-08-02T10:46:43.511Z
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6


    (6)DateTimeFormatter
    • 在JDK8中,引入了一个全新的日期与时间格式器 DateTimeFormatter

    • 正反都能调用 format()

      package com.app.d4_jdk8_time;
      
      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      
      public class Demo06DateTimeFormatter {
          public static void main(String[] args) {
              // 当前日期时间
              LocalDateTime nowDateTime = LocalDateTime.now();
              System.out.println("今天是:" + nowDateTime);
      
              // 格式化日期时间
              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
              // 正向格式化
              String ldt = dtf.format(nowDateTime);
              System.out.println(ldt);
      
              // 反向格式化
              String ldt2 = nowDateTime.format(dtf);
              System.out.println(ldt2);
      
              System.out.println("---------------------------");
              // 定义一个字符串时间
              String dateStr = "2000年08月11日 17:17:17";
              // 未解析前,无法做:得到年月日,时分秒等操作
              // System.out.println(dateStr.getYear());  // 报错!!日期时间未解析
      
              // 解析字符串时间
              DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
              LocalDateTime ldt3 = LocalDateTime.parse(dateStr, dtf2);
              System.out.println(ldt3);
      
              System.out.println(ldt3.getYear());         // 获取年
              System.out.println(ldt3.getDayOfYear());    // 获取此年份中的第几天
              // ....
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      今天是:2022-08-02T18:47:23.912286100
      2022-08-02 18:47:23 周二 下午
      2022-08-02 18:47:23 周二 下午
      ---------------------------
      2000-08-11T17:17:17
      2000
      224
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9


    (7)Period
    • 在JDK8中,我们可以使用以下类计算 日期间隔 差异:java.time.Period

    • 主要是 Period 类方法 getYears(),getMonths(),getDays() 来计算,只能精确到年月日。

    • 用于 LocalDate 之间的比较。

      package com.app.d4_jdk8_time;
      
      import java.time.LocalDate;
      import java.time.Period;
      
      public class Demo07Period {
          public static void main(String[] args) {
              // 今天的日期
              LocalDate today = LocalDate.now();
              System.out.println("今天的日期:" + today);
      
              // 生日的年月日
              LocalDate myDate = LocalDate.of(2002, 2, 10);
              System.out.println("你的生日是:" + myDate);
      
              // 计算日期间隔差
              Period period = Period.between(myDate, today);  // 第一个参数 减去 第二个参数
      
              System.out.println("你活了" + period.getYears() + "年"
                              + "多" + period.getMonths() + "个月"
                              + period.getDays() + "天");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      今天的日期:2022-08-02
      你的生日是:2002-02-10
      你活了20年多5个月23天
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5


    (8)Duration
    • 在JDK8中,我们可以使用以下类来计算 时间间隔 差异:java.time.Duration

    • 提供了使用基于时间的值测量时间量的方法。

    • 用于 LocalDateTime 之间的比较。也可以用于 Instant 之间的比较。

      package com.app.d4_jdk8_time;
      
      import java.time.Duration;
      import java.time.LocalDateTime;
      
      public class Demo08Duration {
          public static void main(String[] args) {
              // 今天的日期时间
              LocalDateTime today = LocalDateTime.now();
              System.out.println("今天是:" + today);
      
              // 生日
              LocalDateTime myDate = LocalDateTime.of(2002, 3, 12, 18,
                                              13, 12, 12);
              System.out.println("生日是:" + myDate);
      
              // 计算时间间隔差
              Duration duration = Duration.between(myDate, today);  // 第二个参数 减去 第一个参数
              System.out.println("两个时间差的天数:" + duration.toDays());
              System.out.println("两个时间差的小时数:" + duration.toHours());
              System.out.println("两个时间差的分钟数:" + duration.toMinutes());
              System.out.println("两个时间差的秒数:" + duration.toSeconds());
              System.out.println("两个时间差的毫秒数:" + duration.toMillis());
              System.out.println("两个时间差的纳秒数:" + duration.toNanos());
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      今天是:2022-08-02T18:48:23.515069300
      生日是:2002-03-12T18:13:12.000000012
      两个时间差的天数:7448
      两个时间差的小时数:178752
      两个时间差的分钟数:10725155
      两个时间差的秒数:643509311
      两个时间差的毫秒数:643509311515
      两个时间差的纳秒数:643509311515069288
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10


    总结

    1、Duration:用于计算两个 “时间” 的间隔;

    2、Period:用于计算两个 “日期” 的间隔。


    (9)ChronoUnit
    • ChronoUnit类可用于在单个时间单位内侧量一段时间,这个工具类是最全的了,可以用于比较所有的时间单位。

      package com.app.d4_jdk8_time;
      
      import java.time.LocalDateTime;
      import java.time.temporal.ChronoUnit;
      
      public class Demo09ChronoUnit {
          public static void main(String[] args) {
              // 今天的日期时间
              LocalDateTime today = LocalDateTime.now();
              System.out.println("今天是:" + today);
      
              // 生日
              LocalDateTime birthDate = LocalDateTime.of(2012, 4, 24,
                                  18, 0, 0);
              System.out.println("生日是:" + birthDate);
      
              System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));
              System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));
              System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));
              System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));
              System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));
              System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));
              System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));
              System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));
              System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));
              System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));
              System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));
              System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));
              System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));
              System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));
              System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      今天是:2022-08-02T18:49:02.791270400
      生日是:2012-04-24T18:00
      相差的年数:10
      相差的月数:123
      相差的天数:3752
      相差的周数:536
      相差的时数:90048
      相差的分数:5402929
      相差的秒数:324175742
      相差的毫秒数:324175742791
      相差的微秒数:324175742791270
      相差的纳秒数:324175742791270400
      相差的半天数:7504
      相差的十年数:1
      相差的世纪(百年)数:0
      相差的千年数:0
      相差的纪元数:0
      
      Process finished with exit code 0
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19


  • 相关阅读:
    07|声学回声消除AEC(1)
    Debezium系列之:PostgreSQL数据库的Debezium连接器
    React 组件实例的三大核心—props
    2022.09 青少年Python等级考试(六级) 编程题部分
    Python-正则表达式技巧-查找目标字符串-范例
    C++中double类型使用技巧
    查找国际顶刊文献有哪些途径?
    pytest(7)-yield与终结函数
    21. python if else 条件判断语句
    设计模式-概述. 类图.软件设计原则详细讲解
  • 原文地址:https://blog.csdn.net/yelitoudu/article/details/126151951