Java学习笔记===》11.JDK相关类

JDK相关类

一、JDK7以前时间相关类

Date 时间

(1)世界标准时间

①格林威治时间/格林尼治时间(Greenwich Mean Time)简称GMT

②目前世界标准时间(UTC)已经替换为:原子钟

(2)中国标准时间

世界标准时间+8小时

(3)时间换算单位

1秒 = 1000毫秒

1毫秒 = 1000微秒

1微秒 = 1000纳秒

1.Date时间类

★Date时间类是一个JDK已经写好的JavaBean类,用来描述时间,精确到毫秒

★利用空参构造创建的对象,默认表示系统当前的时间

★利用有参构造创建的对象,表示指定的时间

(1)关于Date时间类的方法

方法说明
public Date()创建Date对象,表示当前时间
public Date( long date)创建Date对象,表示指定时间
public void setTime(long time)设置/修改毫秒值
public long getTime()获取事件对象的毫秒值
package com_04_myAPI.API09_JDK_DATE;

import java.util.Date;

public class test01_Date {
    public static void main(String[] args) {

        //创建对象表示一个时间
        Date d1 = new Date();
        System.out.println(d1); //Fri Apr 21 20:32:22 HKT 2023

        //创建对象表示一个指定的时间
        Date d2 = new Date(0L);
        System.out.println(d2); //Thu Jan 01 08:00:00 HKT 1970

        //setTime  修改时间
        d2.setTime(10000000L);
        System.out.println(d2); //Thu Jan 01 10:46:40 HKT 1970

        //getTime  获取时间
        long time = d2.getTime();
        System.out.println(time);   //10000000
    }
}
练习

(1)需求1:打印时间原点开始一年之后的时间

(2)需求2:定义任意两个Date对象,比较一下哪个时间在前,哪个时间在后

package com_04_myAPI.API09_JDK_DATE;

import java.util.Date;
import java.util.Random;

public class test02 {
    public static void main(String[] args) {
        /*
        (1)需求1:打印时间原点开始一年之后的时间
        (2)需求2:定义任意两个Date对象,比较一下哪个时间在前,哪个时间在后
         */

        //1.创建一个时间对象,表示时间原点
        Date d1 = new Date(0L);
        //2.获取d1时间的毫秒值形式
        long t1 = d1.getTime();
        //3.在这个基础上,我们要加一年的毫秒值
        t1 = t1 + 1000L * 60 * 60 * 24 * 365;
        //4.把计算之后的时间毫秒值,再设置回d1
        d1.setTime(t1);
        //打印d1
        System.out.println(d1);



        //(2)需求2:定义任意两个Date对象,比较一下哪个时间在前,哪个时间在后
        Random r = new Random();

        Date d2 = new Date(Math.abs(r.nextInt()));
        Date d3 = new Date(Math.abs(r.nextInt()));

        if (d2.getTime() > d3.getTime()){
            System.out.println("第一个时间在后,第二个时间在前面");
        }else if (d2.getTime() < d3.getTime()){
            System.out.println("第一个时间在前面,第二个时间在后面");
        }else {
            System.out.println("两个时间是同一时间");
        }
    }
}

(2)Date时间类小结

①如何创建日期对象

★Date date = new Date();

★Date date = new Date(指定毫秒值);

②如何修改时间对象中的毫秒值

★setTime(毫秒值);

③如何获取时间对象中的毫秒值

★getTime();

2.SimpleDateFormat 格式化时间

(1)作用:

①格式化:把时间变成我们喜欢的格式

2023年10月1日 /2023-10-1/2023/10/1

②解析:把字符串表示的时间变成Date对象

(2)SimpleDateFormat类方法

构造方法说明
public SimpleDateFormat()构造一个SimpleDateFormat,使用默认格式
public SimpleDateFormat(String pattern)构造一个SimpleDateFormat,使用指定的格式
常用方法说明
public final String format(Date date)格式化(日期对象==》字符串)
public Date parse(String source)解析(字符串===》日期对象)

(3)格式化时间形式的常用的模式对应关系

日期
2023-11-11 13:13:13yyyy-MM-DD HH:mm:ss
2023年11月11日 13:13:13yyyy年MM月dd日 HH:mm:ss
y ===》年M ===》月
d ===》日H ===》时
m ===》分是===》秒
package com_04_myAPI.API09_JDK_DATE;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test03_SimpleDateFormat {
    public static void main(String[] args) throws ParseException {
        /*
| 构造方法                                  | 说明                                     |
| --------------------------------------- | ---------------------------------------- |
| public  SimpleDateFormat()              | 构造一个SimpleDateFormat,使用默认格式   |
| public SimpleDateFormat(String pattern) | 构造一个SimpleDateFormat,使用指定的格式 |
| 成员方法                                  | 说明                                 |
| public final String format(Date date)   | 格式化(日期对象==》字符串)             |
| public Date parse(String source)        | 解析(字符串===》日期对象)              |
         */

        //设置格式
        Method1();

        //解析
        //定义一个时间字符串、
        String date1 = "2023-11-11 13:13:13";
        String date2 = "2023年11月11日 13:13:13";
        //1.利用空参构造创建SimpleDateFormat对象,
        //细节:创建的对象的格式要和字符串的格式完全一致,否则会报错
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date d1 = sdf1.parse(date1);
        Date d2 = sdf2.parse(date2);

        System.out.println(d1);
        System.out.println(d2);


    }

    private static void Method1() {
        //1.利用空参构造创建SimpleDateFormat对象,默认格式
        SimpleDateFormat sdf1 = new SimpleDateFormat();
        Date d1 = new Date(0L);
        String str1 = sdf1.format(d1);
        System.out.println(str1);   //1970/1/1 上午8:00

        //2.利用带参构造创建SimpleDateFormat对象,默认格式
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date d2 = new Date(0L);
        String str2 = sdf2.format(d2);
        System.out.println(str2);   //1970年01月01日 08:00:00

        //课堂练习  yyyy年MM月dd日 时:分:秒  星期
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE");
        Date d3 = new Date(0L);
        String str3 = sdf2.format(d1);
        System.out.println(str3);      // 1970年01月01日 08:00:00 星期四
    }
}

(4)练习

需求:

假设,一个人的出生年月日为:2000-11-11

请用字符串表示这个数据,并将其转换为2000年11月11日

package com_04_myAPI.API09_JDK_DATE;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test04 {
    public static void main(String[] args) throws ParseException {
        /*
        需求:
        假设,一个人的出生年月日为:2000-11-11
        请用字符串表示这个数据,并将其转换为2000年11月11日
         */
        String s1 = "2000-11-11";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf1.parse(s1);
        System.out.println(d1);
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
        String str = sdf2.format(d1);
        System.out.println(str);

    }
}

需求:

某品牌秒杀活动开始时间为:2023年11月11日00:00:00,结束时间为2023年11月11日 00:10:00

①小贾下单并付款的时间为:2023年11月11日 00:01:00

②小张下单并付款的时间为:2023年11月11日00:11:00

用代码说明谁没有参加上秒杀活动

package com_04_myAPI.API09_JDK_DATE;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test05 {
    public static void main(String[] args) throws ParseException {
        /*
        需求:
        某品牌秒杀活动开始时间为:2023年11月11日00:00:00,结束时间为2023年11月11日 00:10:00
        ①小贾下单并付款的时间为:2023年11月11日 00:01:00
        ②小张下单并付款的时间为:2023年11月11日00:11:00
        用代码说明谁没有参加上秒杀活动
         */
        //比较两个时间
        //下单比你高付款的时间 跟 开始时间 和 结束时间 比较

        //比较两个时间
        String start = "2023年11月11日 00:00:00";
        String end = "2023年11月11日 00:10:00";
        String jiaOrder ="2023年11月11日 00:01:00";
        String zhangOrder ="2023年11月11日 00:11:00";


        //创建SimpleDateFromat对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        Date jia = sdf.parse(jiaOrder);
        Date zhang = sdf.parse(zhangOrder);


        //获取时间的毫秒值
        long startTime = startDate.getTime();
        long endtTime = endDate.getTime();
        long jiaTime = jia.getTime();
        long zhangTime = zhang.getTime();


        if (zhangTime >= startTime && zhangTime <= endtTime){
            System.out.println("参加秒杀成功");
        }else{
            System.out.println("参加秒杀失败");
        }


        if (jiaTime >= startTime && jiaTime <= endtTime){
            System.out.println("参加秒杀成功");
        }else{
            System.out.println("参加秒杀失败");
        }

    }
}

(5)小结:

①SimpleDateFormat的两个作用

★格式化

★解析

②如何指定格式

★yyyy年MM月dd日 HH:mm:ss

3.Calendar 日历

为什么要学习calendar?

应用场景:

​ 需求:将2023年11月11日增加一个月

(1)概述

★calendar类代表了系统当前时间的日历对象,可以单独修改、获取事件中的年、月、日

★细节:calendar是一个抽象类,不能直接创建对象

(2)获取calendar日历类对象的方法

public static Calendar getInstance(); 获取当前时间的日历对象

(3)Calendar常用方法

方法说明
public final Date getTime();获取日期对象
public final setTime(Date date)给日历设置日期对象
public long getTimeInMillis()拿到时间毫秒值
Public void setTimeInMillis(long millis)给日历设置时间毫秒值
public int get(int filed)取日历中的某个字段信息
public void set (int filed,int value)修改日历的某个字段信息
public void add(int filed,int amount)为某个字段增加/减少指定的值
package com_04_myAPI.API10_Calendar;

import java.util.Calendar;
import java.util.Date;

public class test01 {
    public static void main(String[] args) {
        /*
    (2)获取calendar日历类对象的方法
public  static  Calendar getInstance();     获取当前时间的日历对象

| 方法                                      | 说明                        |
| ----------------------------------------- | --------------------------- |
| public final Date getTime();              | 获取日期对象                |
| public final setTime(Date date)           | 给日历设置日期对象          |
| public long getTimeInMillis()             | 拿到时间毫秒值              |
| Public void setTimeInMillis(long  millis) | 给日历设置时间毫秒值        |
| public int get(int filed)                 | 取日历中的某个字段信息      |
| public void set (int filed,int value)     | 修改日历的某个字段信息      |
| public void add(int filed,int amount)   | 为某个字段增加/减少指定的值 |
         */

        //1.获取日历对象
        //细节1:
        //Calendar是一个抽象类,不能直接new,而是通过一个静态方法获取到子类对象
        //底层原理:会根据系统的不同时区来获取不同的日历对象,默认表示当前时间
        //把事件中的纪元,年,月,日,时,分,秒,星期,等等放到一个数组当中
        //每个索引所代表的的含义
        //0:纪元       1:年      2:月       3:一年中的第几周      4:一个月中的第几周
        //5:一个月中的第几天(日期)    6:

        //细节2:
        //月份:范围0-11,如果获取的月份是0,那么实际月份是0,也就是实际月份等于获取到的月份+1
        //星期:在老外的眼里,星期日是一周中的第一天1(星期日),2(星期一),3(星期二),4(星期三),5(星期四),6(星期五),7(星期六)
        Calendar c1 = Calendar.getInstance();
        System.out.println(c1);

        //2.获取日期对象
        Date time = c1.getTime();
        System.out.println(time);

        //3.给日历设置日期对象
        Date date = new Date(1000*10^11L);
        c1.setTime(date);
        System.out.println(c1);

        //4.拿到时间的毫秒值
        long timeInMillis = c1.getTimeInMillis();
        System.out.println(timeInMillis);

        //5.给日历设置时间毫秒值
        c1.setTimeInMillis(10*10^20L);
        System.out.println(c1);

        //6.取日历中的某个字段信息
        int year = c1.get(Calendar.YEAR);
        int month = c1.get(Calendar.MONTH)+1;
        int dt = c1.get(Calendar.DAY_OF_MONTH);
        int week = c1.get(Calendar.DAY_OF_WEEK);
        System.out.println(year+"年"+month+"月"+dt+"日"+getWeek(week));

        //7.修改日历的某个字段信息
        c1.set(Calendar.YEAR,1999);
        System.out.println(c1);

        //8.为某个字段增加/减少指定的值
        c1.add(Calendar.YEAR,-12);
        System.out.println(c1);
    }

    //查表法:
    //表:容器
    //让数据和索引产生对应关系
    public static String getWeek(int index){
        //定义一个数组,让汉字星期几和数字1-7产生对应关系
        String [] arr = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        //根据索引返回对应的星期
        return arr[index];
    }
}

(4)Calendar日历类小结

1.Calendar表示什么?

★表示一个时间的日历对象

2.如何获取对象

★通过getInstance方法获取对象

3.常见方法

★setXxx :修改

★getXxx :获取

★add:在原有的基础上进行增加或减少

4.细节

★日历类中月份的范围:0-11,平常书写月份+1

★日历类中兴起的特点:星期日是一周中的第一天

二、JDK8新增时间相关类

为什么要学JDK8新增相关时间类呢?

代码层面安全层面
JDK 7代码麻烦 》日期对象(计算、比较) ==》毫秒值在多线程环境下会导致数据安全的问题
JDK 8简单 ==》1.判断的方法 2.计算时间间隔的方法时间日期对象都是不可变的,解决了这个问题(不会改变原有的数据,会新建一个时间日期对象存储新的数据)

1.JDK8新增类

(1)DATE类

①ZoneeId :时区

书写: 洲名/城市名 国家名/城市名

例如:Asia/Shanghai Asia/Taipei Asia/Chongqing

方法名说明
static Set< String > getAvailableZoneIds()获取Java中支持的所有时区
static ZoneId systemDefault()获取系统默认时区
static ZoneId of(String zoneId)获取一个指定时区
package com_04_myAPI.API11_JDK8_increase;

import java.time.ZoneId;
import java.util.Set;

public class ZoneIdTest01 {
    public static void main(String[] args) {
        /*
| 方法名                                      | 说明                     |
| ------------------------------------------- | ------------------------ |
| static Set< String >  getAvailableZoneIds() | 获取Java中支持的所有时区 |
| static ZoneId systemDefault()             | 获取系统默认时区         |
| static ZoneId of(String zoneId)             | 获取一个指定时区         |
         */

        //1.获取所有的时区名称
        Set<String> z1 = ZoneId.getAvailableZoneIds();
        //这里会得到一个Set集合,但是这个集合没有索引,所以不能使用for循环遍历
        System.out.println(z1);
        System.out.println(z1.size());

        //2.获取当前系统的默认时区
        ZoneId z2 = ZoneId.systemDefault();
        System.out.println(z2);

        //3.获取一个指定的时区
        ZoneId z3 = ZoneId.of("America/New_York");
        System.out.println(z3);
    }
}
②Instant :时间戳
方法名说明
static Instance now()获取当前时间的I你Stance对象(标准时间)
static Instance ofXxxx(long epochMilli)根据(秒/毫秒/纳秒)获取Instant对象
ZonedDateTime atZone(ZoneId zone)指定时区
boolean isXxxx(Instant otherInstant)判断系列的方法
Instandt minusXxxx(long millisTosubTract)减少时间系列的方法
Instant plusXxxx(long millisToSubtract)增加时间系列的方法
package com_04_myAPI.API11_JDK8_increase;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Test02_Instant {
    public static void main(String[] args) {
        /*
        | 方法名                                      | 说明                                    |
| ------------------------------------------- | --------------------------------------- |
| static Instance now()                       | 获取当前时间的Instance对象(标准时间) |
| static Instance ofXxxx(long epochMilli)     | 根据(秒/毫秒/纳秒)获取Instant对象     |
| ZonedDateTime atZone(ZoneId zone)         | 指定时区                                |
| boolean isXxxx(Instant otherInstant)        | 判断系列的方法                          |
| Instandt minusXxxx(long millisTosubTract) | 减少时间系列的方法                      |
| Instant plusXxxx(long millisToSubtract)   | 增加时间系列的方法                      |
         */


        //1.获取当前时间的Instance对象(标准时间)
        Instant i1 = Instant.now();
        System.out.println(i1);

        //2.根据(秒/毫秒/纳秒)获取Instant对象(从时间原点开始获取)
        Instant i2 = Instant.ofEpochMilli(100L*100^100);
        Instant i3 = Instant.ofEpochSecond(100L*100^100);    //根据秒获取对象
        Instant i4 = Instant.ofEpochSecond(100L*100^100,100L*100^100); //根据秒、纳秒获取对象
        System.out.println(i2);
        System.out.println(i3);
        System.out.println(i4);

        //3.指定时区
       ZonedDateTime zdt =  Instant.now().atZone(ZoneId.of("America/New_York"));
        System.out.println(zdt);

        //4.判断系列的方法
        Instant i5 = Instant.ofEpochMilli(0L);
        Instant i6 = Instant.ofEpochSecond(10000L);    //根据秒获取对象

        //用于时间的判断
        //isAfter:判断调用者代表的时间是否在参数表示时间的后面
        boolean result1 = i5.isAfter(i6);
        //isBefore:判断调用者代表的时间是否在参数表示时间的前面
        boolean result2 = i5.isBefore(i6);
        System.out.println(result1);
        System.out.println(result2);


        //5.减少时间系列的方法
        Instant i7 = Instant.ofEpochMilli(0L);
        System.out.println(i7);     //1970-01-01T00:00:00Z
        Instant i8 = i7.minusMillis(1000^20L);
        System.out.println(i8);     //1969-12-31T23:59:58.980Z

        //增加时间系列的方法
        Instant i9 = Instant.ofEpochMilli(0L);
        System.out.println(i9);     //1970-01-01T00:00:00Z
        Instant i10 = i9.plusMillis(10000000000L);
        System.out.println(i10);     //1970-04-26T17:46:40Z
    }
}
③ZoneDateTime :带时区的时间
方法名说明
static ZonedDateTime now()获取当前时间的ZonedDateTime对象
static ZonedDateTime ofXxx(…)获取指定时间的ZonedDateTime对象
ZonedDateTime withXxxx(时间)修改时间系列的方法
ZonedDateTime minusXxxx(时间)减少时间系列的方法
ZonedDateTime plusXxxx(时间)增加时间系列的方法
package com_04_myAPI.API11_JDK8_increase;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Test03_ZonedDateTime {
    public static void main(String[] args) {
        /*
| 方法名                          | 说明                            |
| ------------------------------- | ------------------------------- |
| static ZonedDateTime now()      | 获取当前时间的ZonedDateTime对象 |
| static ZonedDateTime ofXxx(...) | 获取指定时间的ZonedDateTime对象 |
| ZonedDateTime withXxxx(时间)    | 修改时间系列的方法              |
| ZonedDateTime minusXxxx(时间) | 减少时间系列的方法              |
| ZonedDateTime plusXxxx(时间)  | 增加时间系列的方法              |
         */

        //1.获取当前时间对象(带时区)
        ZonedDateTime z1 = ZonedDateTime.now();
        System.out.println(z1);     //2023-04-22T16:54:50.664307200+08:00[Asia/Shanghai]

        //2.获取指定时间的对象(带时区)
        //年月日时分秒纳秒方式指定
        ZonedDateTime z2 = ZonedDateTime.of(2023,4,19,20,29,45,000234, ZoneId.of("Asia/Shanghai"));
        System.out.println(z2);     //2023-04-19T20:29:45.000000156+08:00[Asia/Shanghai]

        //3.通过Instant+时区的方式指定获取的时间对象
        Instant instant = Instant.ofEpochMilli(0L);
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        ZonedDateTime z3 = ZonedDateTime.ofInstant(instant,zoneId);
        System.out.println(z3);     //1970-01-01T08:00+08:00[Asia/Shanghai]


        //4.修改系列时间
        ZonedDateTime z4 = z3.withYear(2023);       //2023-01-01T08:00+08:00[Asia/Shanghai] 将年份修改为2023
        //还可以修改年月日时分秒星期等等
        System.out.println(z4);     //2023-04-22T22:58:58.222929100+08:00[Asia/Shanghai]

        //5.减少时间
        ZonedDateTime z5 = z4.minusMonths(2);       //将月份减少两个月
        //还可以修改年月日时分秒星期等等
        System.out.println(z5);     //2022-11-01T08:00+08:00[Asia/Shanghai]

        //6.增加时间
        ZonedDateTime z6 = z5.plusYears(10);        //将年份增加10年
        //还可以修改年月日时分秒星期等等
        System.out.println(z6);     //2032-11-01T08:00+08:00[Asia/Shanghai]

        //细节:
        //JDK8新增的事件对象都是不可变的
        //如果我们修改了,减少了,增加了时间
        //那么调用者是不会发生改变的
        //而是会产生一个新的时间
    }
}

(2)日期格式化类

①DateTimeFoematter :用于时间的格式化和解析

方法名说明
static DateTimeFormatter ofPattern()获取格式对象
String format(时间对象)按照指定方式格式化
package com_04_myAPI.API11_JDK8_increase;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Test04_DateTimeFormatter {
    public static void main(String[] args) {
        /*
| 方法名                               | 说明               |
| ------------------------------------ | ------------------ |
| static DateTimeFormatter ofPattern() | 获取格式对象       |
| String format(时间对象)              | 按照指定方式格式化 |
         */

        //1.获取时间对象
        ZonedDateTime z1 = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));

        //解析/格式化
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss EEEE a");
        //格式化
        String time = dtf1.format(z1);
        System.out.println(time);       //2023年04月22日 17:25:57 星期六 下午
    }
}

(3)日历类

①LocalDate :年、月、日

②LocalTime:时、分、秒

③LocalDateTime :年、月、日、时、分、秒

方法名说明
static XXX now()获取当前时间的对象
static XXX of(…)获取指定时间的对象
get开头的方法获取日历中的年、月、日、时、分、秒等信息
isBefore,isAfter比较两个LocalDate谁在前谁在后
with开头的修改时间系列的方法
minus开头的减少时间系列的方法
plus开头的增加时间系列的方法
LocalDateTime转换===》LocalDate/LocalTime
方法名说明
public LocalDate toLocalDate()LocalDateTime转换成一个LocalDate对象
public LocalTime toLocalTime()LocalDateTime转换成一个LocalTime对象
package com_04_myAPI.API11_JDK8_increase;

import java.time.LocalDate;
import java.time.Month;
import java.time.MonthDay;

public class Test05_LocalDate {
    public static void main(String[] args) {
/*
| 方法名             | 说明                                     |
| ------------------ | ---------------------------------------- |
| static XXX now()   | 获取当前时间的对象                       |
| static XXX of(...) | 获取指定时间的对象                       |
| get开头的方法      | 获取日历中的年、月、日、时、分、秒等信息 |
| isBefore,isAfter  | 比较两个LocalDate谁在前谁在后            |
| with开头的         | 修改时间系列的方法                       |
| minus开头的        | 减少时间系列的方法                       |
| plus开头的         | 增加时间系列的方法                       |

| LocalDateTime转换===》LocalDate/LocalTime |                                      |
| ----------------------------------------- | ------------------------------------ |
| 方法名                                    | 说明                                 |
| public LocalDate toLocalDate()            | LocalDateTime转换成一个LocalDate对象 |
| public LocalTime toLocalTime()            | LocalDateTime转换成一个LocalTime对象 |
 */

        //1.获取当前时间的日历对象
        LocalDate ldt1 = LocalDate.now();
        System.out.println("今天的日期为:"+ldt1);     //今天的日期为:2023-04-22T17:46:58.722469

        //2.获取指定的日历对象
        LocalDate ldt2 = LocalDate.of(2023,12,11);
        System.out.println(ldt2);       //2023-12-11T13:12

        //3.get系列方法获取日历中的每一个属性值
        //获取年
        int year = ldt2.getYear();
        //获取月(方式1)
        Month month = ldt2.getMonth();
        System.out.println("获取到的年份为"+year);     //获取到的年份为2023
        System.out.println("获取到的月份为"+month);        //获取到的月份为DECEMBER
        //方式2
        int mon = ldt2.getMonthValue();
        System.out.println("获取到的月份为"+mon);      //获取到的月份为12


        //4.is开头的方法表示判断
        System.out.println(ldt2.isBefore(ldt1));        //false
        System.out.println(ldt2.isAfter(ldt1));     //true

        //5.with开头的方法表示修改,只修改年月日
        LocalDate ldt3 = ldt2.withYear(2099);
        System.out.println(ldt3);       //2099-12-11T13:12

        //6.minus开头的方法表示减少,只能减少年月日
        LocalDate ldt4 = ldt3.minusYears(20);
        System.out.println(ldt4);       //2079-12-11T13:12

        //7.plus开头的方法表示增加,只能增加年月日
        LocalDate ldt5 = ldt3.plusYears(20);
        System.out.println(ldt5);       //2119-12-11T13:12


        //练习:判断今天是不是自己的生日
        LocalDate birthday = LocalDate.of(2000,12,18);
        LocalDate today = LocalDate.now();
        MonthDay check = MonthDay.of(birthday.getMonthValue(),birthday.getDayOfMonth());
        MonthDay now = MonthDay.from(today);

        System.out.println("今天是你的生日吗"+birthday.equals(now));
    }
}
package com_04_myAPI.API11_JDK8_increase;

import java.time.LocalTime;

public class Test06_LocalTime {
    public static void main(String[] args) {
        //1.获取本地的日历对象(包含时分秒)
        LocalTime lt1 = LocalTime.now();
        System.out.println("当前时间为"+lt1);

        //2.get获取
        int hour = lt1.getHour();
        int minute = lt1.getMinute();
        int second = lt1.getSecond();
        int nano = lt1.getNano();
        System.out.println("当前是"+hour+"时"+minute+"分"+second+"秒"+nano+"纳秒");

        //3.指定时间
        System.out.println(LocalTime.of(8,20));
        System.out.println(LocalTime.of(8,20,30));
        System.out.println(LocalTime.of(8,20,30,150));
        LocalTime lt2 = LocalTime.of(8,20,30,150);

        //4.is的用法
        System.out.println(lt1.isAfter(lt2));
        System.out.println(lt1.isBefore(lt2));

        //5.with修改(只能修改时分秒)
        System.out.println(lt2.withHour(12));

        //6.minus减少时间(只能修改时分秒)
        System.out.println(lt2.minusMinutes(23));

        //7.plus增加时间(只能修改时分秒)
        System.out.println(lt2.plusSeconds(100));

    }
}
package com_04_myAPI.API11_JDK8_increase;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Test07_LocalDateTime {
    public static void main(String[] args) {
        // 当前时间的的日历对象(包含年月日时分秒)
        LocalDateTime nowDateTime = LocalDateTime.now();

        System.out.println("今天是:" + nowDateTime);//今天是:
        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());//纳秒
        // 日:当年的第几天
        System.out.println("dayofYear:" + nowDateTime.getDayOfYear());
        //星期
        System.out.println(nowDateTime.getDayOfWeek());
        System.out.println(nowDateTime.getDayOfWeek().getValue());
        //月份
        System.out.println(nowDateTime.getMonth());
        System.out.println(nowDateTime.getMonth().getValue());

        LocalDate ld = nowDateTime.toLocalDate();
        System.out.println(ld);

        LocalTime lt = nowDateTime.toLocalTime();
        System.out.println(lt.getHour());
        System.out.println(lt.getMinute());
        System.out.println(lt.getSecond());
    }
}

(4)工具类

①Duration :时间间隔(秒、纳秒)

package com_04_myAPI.API11_JDK8_increase;

import java.time.LocalDate;
import java.time.Period;

public class Test08_Period {
    public static void main(String[] args) {
        // 当前本地 年月日
        LocalDate today = LocalDate.now();
        System.out.println(today);

        // 生日的 年月日
        LocalDate birthDate = LocalDate.of(2000, 1, 1);
        System.out.println(birthDate);

        Period period = Period.between(birthDate, today);//第二个参数减第一个参数

        System.out.println("相差的时间间隔对象:" + period);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());

        System.out.println(period.toTotalMonths());
    }
}

②Period :时间间隔(年、月、日)

package com_04_myAPI.API11_JDK8_increase;

import java.time.Duration;
import java.time.LocalDateTime;

public class Test09_Duration {
    public static void main(String[] args) {
        // 本地日期时间对象。
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // 出生的日期时间对象
        LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
        System.out.println(birthDate);

        Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数
        System.out.println("相差的时间间隔对象:" + duration);

        System.out.println("============================================");
        System.out.println(duration.toDays());//两个时间差的天数
        System.out.println(duration.toHours());//两个时间差的小时数
        System.out.println(duration.toMinutes());//两个时间差的分钟数
        System.out.println(duration.toMillis());//两个时间差的毫秒数
        System.out.println(duration.toNanos());//两个时间差的纳秒数
    }
}

③ChronoUnit :时间间隔,所有单位

package com_04_myAPI.API11_JDK8_increase;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Test10_ChronoUnit {
    public static void main(String[] args) {
        // 当前时间
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);
        // 生日时间
        LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,
                0, 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.WEEKS.between(birthDate, today));
        System.out.println("相差的天数:" + ChronoUnit.DAYS.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));
    }
}

2.小结

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6cPYaX7w-1686128382616)(D:\java笔记\笔记图片\JDK8新增类.png)]

三、包装类

包装类:基本数据类型对应的引用数据类型(对象)

内存:

在这里插入图片描述

通俗的说,就是用一个对象将基本数据类型给包起来

1.常用的包装类

基本数据类型包装类
byteByte
shortShort
charCharacter
intInteger
booleanBoolean
longLong
floatFloat
doubleDouble

在JDK5以前需要我们主动去创建获取对象

package com_04_myAPI.API12_Wrap;

public class Test01_Integer_beforeJDK5 {
    public static void main(String[] args) {
        /*
            public Integer(int value) 根据传递的整数创建一个Integer对象
            public Integer(String s) 根据传递的字符串创建一个Integer对象
            public static Integer valueOf(int i) 根据传递的整数创建一个Integer对象
            public static Integer valueof(String s) 根据传递的字符串创建一个Integer对象
            public static Integer valueof(String s, int radix) 根据传递的字符串和进制创建一个Integer对象
        */

        //1.利用构造方法获取Integer的对象(JDK5以前的方式)
        Integer i1 = new Integer(1);
        Integer i2 = new Integer("1");
        System.out.println(i1);
        System.out.println(i2);

        //2.利用静态方法获取Integer的对象(JDK5以前的方式)
        Integer i3 = Integer.valueOf(123);
        Integer i4 = Integer.valueOf("123");
        Integer i5 = Integer.valueOf("123", 8);

        System.out.println(i3);
        System.out.println(i4);
        System.out.println(i5);

        //3.这两种方式获取对象的区别(掌握)
        //底层原理:
        //因为在实际开发中,-128~127之间的数据,用的比较多。
        //如果每次使用都是new对象,那么太浪费内存了
        //所以,提前把这个范围之内的每一个数据都创建好对象
        //如果要用到了不会创建新的,而是返回已经创建好的对象。
        Integer i6 = Integer.valueOf(127);
        Integer i7 = Integer.valueOf(127);
        System.out.println(i6 == i7);//true

        Integer i8 = Integer.valueOf(128);
        Integer i9 = Integer.valueOf(128);
        System.out.println(i8 == i9);//false

        //因为看到了new关键字,在Java中,每一次new都是创建了一个新的对象
        //所以下面的两个对象都是new出来,地址值不一样。
        Integer i10 = new Integer(127);
        Integer i11 = new Integer(127);
        System.out.println(i10 == i11);

        Integer i12 = new Integer(128);
        Integer i13 = new Integer(128);
        System.out.println(i12 == i13);
    }
}
package com_04_myAPI.API12_Wrap;

public class Test02_Intrger {
    public static void main(String[] args) {
        //在以前,包装类如何进行计算
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(2);

        //要把两个数据进行相加得到结果
        //注意对象之间按不能直接进行计算的
        //步骤:
        //1.把对象进行拆箱,变成基本数据类型

        //2.进行计算
        //3.把得到的结果再进行装箱
        int sum = i1.intValue()+i2.intValue();
        Integer i3 = new Integer(sum);
        System.out.println(i3);
    }
}
package com_04_myAPI.API12_Wrap;

public class Test03_Integer_AfterJDK5 {
    public static void main(String[] args) {
        //再jdk5的时候提出了一个机制:自动装箱、自动拆箱
        //自动装箱:把基本数据类型会自动的变成其对应的包装类
        //自动拆箱:将包装类自动的变成其基本数据类型

        Integer i1 = 10;    //自动装箱动作
        //在底层,此时还会自动调用静态方法valueof得到一个Integer对象,只不过这个动作不需要我们自己去操作了

        Integer i2 = new Integer(10);

        int i = i2;  //自动拆箱动作

        //在JDK5以后interesting和integer可以看作是同一个东西,因为在内部可以自动转化

    }
}

2.包装类的作用:

(1)什么是包装类

基本数据类型对应的对象

(2)JDK5以后对包装类新增了什么特性

自动装箱、自动拆箱

(3)我们以后如何获取包装类对象?

不需要new,不需要调用方法,直接赋值即可

3.Integer成员方法

方法名说明
public static String toBinaryString(int i)得到二进制
public static String toOctslString(int i)得到八进制
public static String toHexString(int i)得到十六进制
public static int parseInt(String s)将字符串类型的整数转换成int类型的整数
package com_04_myAPI.API12_Wrap;

public class Test04_Integer {
    public static void main(String[] args) {
/*
| 方法名                                     | 说明                                  |
| ------------------------------------------ | ------------------------------------- |
| public static String toBinaryString(int i) | 得到二进制                            |
| public static String toOctslString(int i)  | 得到八进制                            |
| public static String toHexString(int i)    | 得到十六进制                          |
| public static int parseInt(String s)       | 将字符串类型的整数转换成int类型的整数 |
 */

        //1.把证整数转成二进制
        String er = Integer.toBinaryString(100);
        1.把证整数转成八进制
        String ba = Integer.toOctalString(100);
        1.把证整数转成十六进制
        String sixteen = Integer.toHexString(100);

        System.out.println(er);
        System.out.println(ba);
        System.out.println(sixteen);

        //将字符串类型的整数转换成int类型的整数
        //在Java中,Java是一门强类型语言,也就是每种数据在Java中都有各自的数据类型
        //在计算的时候,如果不是同一种书类型,是无法直接计算的
        int i = Integer.parseInt("1000");
        System.out.println(i);
        //细节1:在类型转换的时候,括号中的参数只能是数字不能是其他,否则代码会报错
        //细节2:8中包装类中,除了Character都有对应的parseXxx的方法,进行类型转换

        String str = "239.98";
        float f = Float.parseFloat(str);
        System.out.println(f);

        

    }
}
小练习
package com_04_myAPI.API12_Wrap;

import java.util.Scanner;

public class Test05_Warp_Scanner {
    public static void main(String[] args) {
        //改写键盘录入的代码
        //键盘录入
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        /* String str = sc.next();
        System.out.println(str);*/
        //弊端:
        //当我们在使用next,nextInt,nextDouble在接收数据的时候,遇到空格,回车,制表符的时候就停止了
        //键盘录入的是123 123 那么此时只能接收到空格前面的数据
        //我想要的是接收一整行数据
        //约定:
        //以后我们如果想要键盘录入,不管什么类型,统一使用nextLine
        //特点:遇到回车才停止
        String line = sc.nextLine();
        System.out.println(line);
        double v = Double.parseDouble(line);
        System.out.println(v);
    }
}

四、综合练习

1.键盘录入一些1-100之间的数据,并添加加到集合当中,直到集合中所有数据的和超过200为止

package com_04_myAPI.API12_Wrap;

import java.util.ArrayList;
import java.util.Scanner;

public class Test06_pratice1 {
    public static void main(String[] args) {
        /*
    需求:.键盘录入一些1-100之间的数据,并添加加到集合当中,直到集合中所有数据的和超过200为止
     */

        //1.创建一个集合用来添加数据
        ArrayList<Integer> list = new ArrayList();
        //2.创建键盘录入对象
        Scanner sc = new Scanner(System.in);
        //接受键盘录入的数据添加到集合
        while (true){
            System.out.println("请输入一个整数");
            String numStr = sc.nextLine();
            int num = Integer.parseInt(numStr);
            if(num<0 || num>100){
                System.out.println("当前输入的数据超出1-100的范围,请重新输入");
                continue;
            }else{
                //添加到集合当中
                //细节:这里的num是基本数据类型,集合里面的数据是Integer
                //在添加数据的时候出发了自动装箱
                list.add(num);  //list.add(Integer.valueOf(num));  这里的两句代码效果是一样的
                //统计集合中所有的数据和
                int sum = getSum(list);
                if (sum>200){
                    System.out.println("集合中所有的数据和满足要求");
                    break;
                }else {
                    continue;
                }
            }
        }
        //验证:遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    private static int getSum(ArrayList<Integer> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            int num = list.get(i);
            sum += num;
        }
        return sum;
    }
}

2.实现parseInt方法的效果,将字符串形式的数据转成整数。

要求:字符串只能是数字不能有其他字符

最少一位,最多10位,不能以0开头

package com_04_myAPI.API12_Wrap;

import java.util.Scanner;

public class Test07_pratice2 {
    public static void main(String[] args) {
        /*
        需求:2.实现parseInt方法的效果,将字符串形式的数据转成整数。
        要求:字符串只能是数字不能有其他字符
        最少一位,最多10位,不能以0开头
         */

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一串数字");
        String str = sc.nextLine();
        //先校验错误的数据
        if (!str.matches("[1-9]\\d{0,9}")){
            System.out.println("格式有误");
            //再书写数据正确的情况下的代码
        }else{
            System.out.println("数据格式正确");
            //定义一个变量,表示最终的结果
            int number = 0;
            //遍历字符串得到里面的每一个字符
            for (int i = 0; i < str.length(); i++) {
                int num = str.charAt(i) - '0';
                //System.out.print(num+",");
                //再将每一位数字放到number中
                number = number * 10 + num;       
            }
            System.out.println(number);
        }
    }
}

3.定义一个方法试下toBinaryString方法的效果,将一个十进制数转成字符串表示的二进制

解题思路:除基取余法

不断地除以基数(几进制,基数就是几),得到余数

知道商为0,再将余数倒着拼起来即可

package com_04_myAPI.API12_Wrap;

public class Test08_pratice3 {
    public static void main(String[] args) {
        /*

            定义一个方法自己实现toBinaryString方法的效果,将一个十进制整数转成字符串表示的二进制

         */
        System.out.println(tobinarystring(123));
        System.out.println(Integer.toBinaryString(123));
    }


    public static String tobinarystring(int number) {//6
        //核心逻辑:
        //不断的去除以2,得到余数,一直到商为日就结束。
        //还需要把余数倒着拼接起来

        //定义一个StringBuilder用来拼接余数
        StringBuilder sb = new StringBuilder();
        //利用循环不断的除以2获取余数
        while (true) {
            if (number == 0) {
                break;
            }
            //获取余数 %
            int remaindar = number % 2;//倒着拼接
            sb.insert(0, remaindar);
            //除以2 /
            number = number / 2;
        }
        return sb.toString();
    }
}

4.请用代码实现计算你活了多少天,用jdk7和jdk8两种完成

package com_04_myAPI.API12_Wrap;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Test09_pratice {
    public static void main(String[] args) throws ParseException {
        //请用代码实现计算你活了多少天,用jdk7和jdk8两种完成

        //jdk7
        //规则:只要对时间进行计算或者判断,都需要先获取当前时间的毫秒值

        //1.计算出生年月日的毫秒值
        String birthday = "2000年12月28日";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = sdf.parse(birthday);
        long birthdayTime = date.getTime();
        System.out.println(birthdayTime);
        //2.当前时间的毫秒值
        long now = System.currentTimeMillis();

        //计算
        long lifeDate = (now - birthdayTime)/1000/60/60/24;
        System.out.println("我一共活了"+lifeDate+"天");


        //jdk8
        LocalDate ld1 = LocalDate.of(2000,12,28);
        LocalDate ld2 = LocalDate.now();

        long days = ChronoUnit.DAYS.between(ld1, ld2);
        System.out.println("我一共活了"+days+"天");

    }
}

5.判断任意的一个年份是闰年还是平年

要求:用jdk7和jdk8两种方式判断

提示:二月有29天是闰年

​ 一年有366天是闰年

package com_04_myAPI.API12_Wrap;

import java.time.LocalDate;
import java.util.Calendar;

public class Test10_pratice {
    public static void main(String[] args) {
        /*
            判断任意的一个年份是闰年还是平年要求:用JDK7和JDK8两种方式判断提示:
            二月有29天是闰年一年有366天是闰年
        */

        //jdk7
        //我们可以把时间设置为2000年3月1日
        Calendar c = Calendar.getInstance();
        c.set(2000, 2, 1);
        //月份的范围:0~11
        //再把日历往前减一天
        c.add(Calendar.DAY_OF_MONTH, -1);
        //看当前的时间是28号还是29号?
        int day = c.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);


        //jdk8
        //月份的范围:1~12
        //设定时间为2000年的3月1日
        LocalDate ld = LocalDate.of(2001, 3, 1);
        //把时间往前减一天
        LocalDate ld2 = ld.minusDays(1);
        //获取这一天是一个月中的几号
        int day2 = ld2.getDayOfMonth();
        System.out.println(day2);

        //true:闰年
        //false:平年
        System.out.println(ld.isLeapYear());


    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值