day15_Java常用API

1、StringBuilder

1.1 StringBuilder类概述

StringBuilder是一个可变的字符串类,我们可以把它看成是一个容器,这里的可变指的是 StringBuilder对象中的

内容是可变的

1.2 StringBuilder类和String类区别

  • String类:内容是不可变的
  • StringBuilder类:内容是可变的

1.3 StringBuilder类的构造方法

方法名说明
public StringBuilder()创建一个空白可变字符串对象,不含有任何内容
public StringBuilder(String str)根据字符串的内容,来创建可变字符串对象

代码演示

public class StringBuilderDemo01{
    publicstaticvoidmain(String[]args){
        //public StringBuilder():创建一个空白可变字符串对象,不含有任何内容
        StringBuilder sb=new StringBuilder();
        System.out.println("sb:"+sb);
        System.out.println("sb.length():"+sb.length());
        //public StringBuilder(Stringstr):根据字符串的内容,来创建可变字符串对象   
        StringBuilder sb2=new StringBuilder("hello");
        System.out.println("sb2:"+sb2);
        System.out.println("sb2.length():"+sb2.length());
    }
}

1.4 StringBuilder类常见方法

1.4.1 添加和反转方法

方法名说明
public StringBuilderappend(Object obj)添加数据,并返回对象本身
public StringBuilderreverse()返回相反的字符序列
/*
    StringBuilder 的添加和反转方法
        public StringBuilder append(任意类型):添加数据,并返回对象本身
        public StringBuilder reverse():返回相反的字符序列
 */
public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //创建对象
        StringBuilder sb = new StringBuilder();
​
        //public StringBuilder append(任意类型):添加数据,并返回对象本身
        // StringBuilder sb2 = sb.append("hello");
        
        // System.out.println("sb:" + sb);
        // System.out.println("sb2:" + sb2);
        // System.out.println(sb == sb2);
        //
        // sb.append("hello");
        // sb.append("world");
        // sb.append("java");
        // sb.append(100);
​
        //链式编程
        sb.append("hello").append("world").append("java").append(100);
​
        System.out.println("sb:" + sb);
​
        //public StringBuilder reverse():返回相反的字符序列
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}
​

1.4.2 转换方法

方法名说明
public String toString()将StringBuilder转换为String
//创建对象
StringBuilder sb = new StringBuilder("Hello");
String str = sb.toString();

1.5 StringBuilder和String相互转换

  • StringBuilder转换为String
    public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String
  • String转换为StringBuilder
    public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder

  • 示例代码

    /*
        StringBuilder 转换为 String
            public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String
    ​
        String 转换为 StringBuilder
            public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder
     */
    public class StringBuilderDemo02 {
        public static void main(String[] args) {
            /*
                //StringBuilder 转换为 String
                StringBuilder sb = new StringBuilder();
                sb.append("hello");
    ​
                // String s = sb; //这个是错误的做法
    ​
                //public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String
                String s = sb.toString();
                System.out.println(s);
            */
    ​
            //String 转换为 StringBuilder
            String s = "hello";
    ​
            // StringBuilder sb = s; //这个是错误的做法
    ​
            //public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder
            StringBuilder sb = new StringBuilder(s);
    ​
            System.out.println(sb);
        }
    }
    ​

1.6 StringBuilder案例

1.6.1 字符串拼接案例

  • 案例需求

    定义一个方法,把 int 数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,并在控制台输出结果。例如,数组为int[] arr = {1,2,3}; ,执行方法后的输出结果为:[1, 2, 3]

  • 代码实现
    /*
        需求:
            定义一个方法,把 int 数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,并在控制台输出结果。
            例如,数组为int[] arr = {1,2,3}; ,执行方法后的输出结果为:[1, 2, 3]
    ​
        思路:
            1:定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
            2:定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回。
              返回值类型 String,参数列表 int[] arr
            3:在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
            4:调用方法,用一个变量接收结果
            5:输出结果
     */
    public class StringBuilderTest01 {
        public static void main(String[] args) {
            //定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
            int[] arr = {1, 2, 3};
    ​
            //调用方法,用一个变量接收结果
            String s = arrayToString(arr);
    ​
            //输出结果
            System.out.println("s:" + s);
        }
    ​
        //定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回
        /*
            两个明确:
                返回值类型:String
                参数:int[] arr
         */
        public static String arrayToString(int[] arr) {
            //在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            for(int i=0; i<arr.length; i++) {
                if(i == arr.length-1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(", ");
                }
            }
            sb.append("]");
            String s = sb.toString();
            return  s;
        }
    }

1.6.2 字符串反转案例

  • 案例需求

    定义一个方法,实现字符串反转。键盘录入一个字符串,调用该方法后,在控制台输出结果

    例如,键盘录入abc,输出结果 cba

  • 代码实现
    import java.util.Scanner;
    ​
    /*
        需求:
            定义一个方法,实现字符串反转。键盘录入一个字符串,调用该方法后,在控制台输出结果
            例如,键盘录入abc,输出结果 cba
    ​
        思路:
            1:键盘录入一个字符串,用 Scanner 实现
            2:定义一个方法,实现字符串反转。返回值类型 String,参数 String s
            3:在方法中用StringBuilder实现字符串的反转,并把结果转成String返回
            4:调用方法,用一个变量接收结果
            5:输出结果
     */
    public class StringBuilderTest02 {
        public static void main(String[] args) {
            //键盘录入一个字符串,用 Scanner 实现
            Scanner sc = new Scanner(System.in);
    ​
            System.out.println("请输入一个字符串:");
            String line = sc.nextLine();
    ​
            //调用方法,用一个变量接收结果
            String s = myReverse(line);
    ​
            //输出结果
            System.out.println("s:" + s);
        }
    ​
        //定义一个方法,实现字符串反转。返回值类型 String,参数 String s
        /*
            两个明确:
                返回值类型:String
                参数:String s
         */
        public static String myReverse(String s) {
            //在方法中用StringBuilder实现字符串的反转,并把结果转成String返回
            //String --- StringBuilder --- reverse() --- String
            // StringBuilder sb = new StringBuilder(s);
            // sb.reverse();
            // String ss = sb.toString();
            // return ss;
    ​
           return new StringBuilder(s).reverse().toString();
        }
    }
    ​

2、Math类

2.1 Math类概述

java.lang.Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。类似这样的工具

类,其所有方法均为静态方法,并且不会创建对象,调用起来非常简单。

2.2 Math类常用方法

方法名说明
Math.PI常量,圆周率
public static double abs(double num)取绝对值
public static double ceil(double num)向上取整
public static double floor(double num)向下取整
public static long round(double num)四舍五入
public static int max(int a, int b)求最大值
public static int min(int a, int b)求最小值
public static double pow(double a, double b)求a的b次幂
public static double random()随机数,随机的范围[0,1)

代码演示

public class MathDemo{
    public static void main(String[] args){
        double d1 = Math.abs(‐5); //d1的值为5 
        double d2 = Math.abs(5); //d2的值为5
​
        double d1 = Math.ceil(3.3); //d1的值为 4.0
        double d2 = Math.ceil(‐3.3); //d2的值为 ‐3.0 
        double d3 = Math.ceil(5.1); //d3的值为 6.0
​
        double d1 = Math.floor(3.3); //d1的值为3.0
        double d2 = Math.floor(‐3.3); //d2的值为‐4.0 
        double d3 = Math.floor(5.1); //d3的值为 5.0
​
        long d1 = Math.round(5.5); //d1的值为6.0
        long d2 = Math.round(5.4); //d2的值为5.0
    }
}

3、Arrays类

3.1 Arrays类概述

java.util.Arrays 此类包含用来操作数组的各种方法,比如排序和搜索等。其所有方法均为静态方法,调用起来非常简单。

3.2 Arrays类概述

方法名说明
public static String toString(int[] a)返回指定数组内容的字符串表示形式。
public static void sort(int[] a)对指定的int型数组按数字升序进行排序。
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)数组拷贝

代码演示

public class ArraysDemo{
    public static void main(String[] args) {
        // 定义int 数组
        int[] arr  =  {2,34,35,4,657,8,69,9};
        // 打印数组,输出地址值
        System.out.println(arr); // [I@2ac1fdc4

        // 数组内容转为字符串
        String s = Arrays.toString(arr);
        // 打印字符串,输出内容
        System.out.println(s); // [2, 34, 35, 4, 657, 8, 69, 9]

        // 定义int 数组
        int[] arr  =  {24, 7, 5, 48, 4, 46, 35, 11, 6, 2};
        System.out.println("排序前:"+ Arrays.toString(arr)); // 排序前:[24,7,5,48,4,46,35,11,6,2]

        // 升序排序
        Arrays.sort(arr);
        System.out.println("排序后:"+ Arrays.toString(arr));// 排序后:[2,4,5,6,7,11,24,35,46,48]
    }
}

3.3 Arrays案例

  • 需求

    请使用Arrays相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印。

  • 代码演示
    public class ArraysTest {
        public static void main(String[] args) {
            // 定义随机的字符串
            String line = "ysKUreaytWTRHsgFdSAoidq";
            // 转换为字符数组
            char[] chars = line.toCharArray();
    
            // 升序排序
            Arrays.sort(chars);
            // 反向遍历打印
            for (int i =  chars.length‐1; i >= 0 ; i‐‐) {
                System.out.print(chars[i]+" "); // y y t s s r q o i g e d d a W U T S R K H F A     
            }
        }
    }

4、System类

4.1 System类概述

java.lang.System类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作,在System类的API文档中,

常用的方法有:

方法说明
public static long currentTimeMillis()返回以毫秒为单位的当前时间。
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)将数组中指定的数据拷贝到另一个数组中。
public static void exit(int status)l 用来结束正在运行的Java程序。参数传入一个数字即可。通常传入0记为正常状态,其他为异常状态

4.2 currentTimeMillis方法

实际上,currentTimeMillis方法就是 获取当前系统时间与1970年01月01日00:00点之间的毫秒差值

import java.util.Date;

public class SystemDemo {
    public static void main(String[] args) {
       	//获取当前时间毫秒值
        System.out.println(System.currentTimeMillis()); // 1516090531144
    }
}

4.3 arraycopy方法

数组的拷贝动作是系统级的,性能很高。System.arraycopy方法具有5个参数,含义分别为:

参数序号参数名称参数类型参数含义
1srcObject源数组
2srcPosint源数组索引起始位置
3destObject目标数组
4destPosint目标数组索引起始位置
5lengthint复制元素个数

  • 案例

    将src数组中前3个元素,复制到dest数组的前3个位置上复制元素前:src数组元素[1,2,3,4,5],dest数组元素[6,7,8,9,10]复制元素后:src数组元素[1,2,3,4,5],dest数组元素[1,2,3,9,10]

  • 代码实现
    public class Demo11SystemArrayCopy {
        public static void main(String[] args) {
            int[] src = new int[]{1,2,3,4,5};
            int[] dest = new int[]{6,7,8,9,10};
            System.arraycopy( src, 0, dest, 0, 3);
            /*代码运行后:两个数组中的元素发生了变化
             src数组元素[1,2,3,4,5]
             dest数组元素[1,2,3,9,10]
            */
        }
    }

5、包装类

5.1 包装类概述

Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下:

基本类型对应的包装类(位于java.lang包中)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

5.2 装箱与拆箱

基本类型与对应的包装类对象之间,来回转换的过程称为【装箱】与【拆箱】:

  • 什么是装箱:

    从基本类型转换为对应的包装类对象。

  • 什么是拆箱:

    从包装类对象转换为对应的基本类型。

以Integer与int为例演示他们之间的转换:

  • 数值 转 包装对象
    Integer i = new Integer(4);//使用构造函数函数
    Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法
  • 包装对象 转 数值
    int num = i.intValue();

5.3 自动装箱与自动拆箱

由于我们经常要做基本类型与包装类之间的转换,从Java 5(JDK 1.5)开始,基本类型与包装类的装箱、拆箱动作可以自动完成。例如:

Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);
i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5;
//加法运算完成后,再次装箱,把基本数值转成对象。

5.4 基本类型与字符串之间的转换

  • 基本类型转换为String
    • 基本类型的值+""

      int i = 10;
      String s = i +"";
    • 包装类的静态方法toString(参数)

      static String toString(int i) 返回一个表示指定整数的 String 对象

      String s =  Integer.toString(10);
    • String类的静态方法valueOf(参数)

      static String valueOf(int i) 返回 int 参数的字符串表示形式。

      String s = String.valueOf(20);
      System.out.println(s+20);

  • String转换成对应的基本类型

    将字符串的数组转换成int类型的数据

    public class Demo18WrapperParse {
        public static void main(String[] args) {
            int num = Integer.parseInt("100");
        }
    }

    除了Integer类之外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型:

    方法说明
    public static byte parseByte(String s)将字符串参数转换为对应的byte基本类型。
    public static short parseShort(String s)将字符串参数转换为对应的short基本类型。
    public static int parseInt(String s)将字符串参数转换为对应的int基本类型。
    public static long parseLong(String s)将字符串参数转换为对应的long基本类型。
    public static float parseFloat(String s)将字符串参数转换为对应的float基本类型。
    public static double parseDouble(String s)将字符串参数转换为对应的double基本类型。
    public static boolean parseBoolean(String s)将字符串参数转换为对应的boolean基本类型。

  • 注意事项

    如果字符串参数的内容无法正确转换为对应的基本类型,则会抛出java.lang.NumberFormatException异常。

6、BigInteger类

6.1 BigInteger类概述

java中long型为最大整数类型,对于超过long型的数据如何去表示呢?在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigInteger对象.在BigInteger类中,实现四则运算都是方法来实现,并不是采用运算符.

6.2 BigInteger类的构造方法

方法说明
public BigInteger(String val)将字符串的数组封装成BigInteger对象

7.3 BigInteger类的常用方法

方法说明
public BigInteger add(BigInteger val)两个BigInteger进行相加,并返回BigInteger
public BigInteger subtract(BigInteger val)两个BigInteger进行相减,并返回BigInteger
public BigInteger multiply(BigInteger val)两个BigInteger进行相乘,并返回BigInteger
public BigInteger divide(BigInteger val)两个BigInteger进行相除,并返回BigInteger

6.4 BigInteger类的四则运算演示

public class BigIntegerDemo{
    public static void main(String[] args) {
        //大数据封装为BigInteger对象
        BigInteger big1 = new BigInteger("12345678909876543210");
        BigInteger big2 = new BigInteger("98765432101234567890");
        //add实现加法运算
        BigInteger bigAdd = big1.add(big2);
        //subtract实现减法运算
        BigInteger bigSub = big1.subtract(big2);
        //multiply实现乘法运算
        BigInteger bigMul = big1.multiply(big2);
        //divide实现除法运算
        BigInteger bigDiv = big2.divide(big1);
    }
}

7、BigDecimal类

7.1 BigDecimal类的引入

  • 在程序中执行下列代码,会出现什么问题?
System.out.println(0.09 + 0.01);
System.out.println(1.0 - 0.32);
System.out.println(1.015 * 100);
System.out.println(1.301 / 100);

doublefloat类型在运算中很容易丢失精度,造成数据的不准确性,Java提供我们BigDecimal类可以实现浮点数据的高精度运算

7.2 BigDecimal类的构造方法

方法名说明
public BigDecimal(String val)将String类型的数组封装为BigDecimal对象

建议浮点数据以字符串形式给出,因为参数结果是可以预知的

7.3 BigDecimal类的常用方法

方法名说明
public BigDecimal add(BigDecimal augend)浮点类型数据相加操作
public BigDecimal subtract(BigDecimal subtrahend)浮点类型数据相减操作
public BigDecimal multiply(BigDecimal multiplicand)浮点类型数据相乘操作
public BigDecimal divide(BigDecimal divisor)浮点类型数据相除操作
public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)浮点类型数据相除操作,按照指定的模式,保留几位小数
public static void main(String[] args) {

    //大数据封装为BigDecimal对象
    BigDecimal big1 = new BigDecimal("0.09");
    BigDecimal big2 = new BigDecimal("0.01");
    //add实现加法运算
    BigDecimal bigAdd = big1.add(big2);

    BigDecimal big3 = new BigDecimal("1.0");
    BigDecimal big4 = new BigDecimal("0.32");
    //subtract实现减法运算
    BigDecimal bigSub = big3.subtract(big4);

    BigDecimal big5 = new BigDecimal("1.105");
    BigDecimal big6 = new BigDecimal("100");
    //multiply实现乘法运算
    BigDecimal bigMul = big5.multiply(big6);
}

对于浮点数据的除法运算,和整数不同,可能出现无限不循环小数,因此需要对所需要的位数进行保留和选择舍入模式

public static void main(String[] args) {

        BigDecimal big1 = new BigDecimal("10.0");
        BigDecimal big2 = new BigDecimal("3.0");
		
    	// 做除法运算,结果是什么呢?
        // BigDecimal divide = big1.divide(big2);
        // System.out.println(divide); // 发现会报错,数学异常ArithmeticException
    	/*
    		什么问题导致的呢?
    			BigDecimal计算的结果要的是一个精确的数,而10/3 是一个无限循环的,不能够精确,所以就报错了!
    		此时我们要用到另一个重载的方法,让计算的结果有一个精确度!
		*/
    	/*
    		参数一:表示参与运算的另外一个对象
    		参数二:表示小数点后精确多少位
    		参数三:舍入模式
    			   BigDecimal.ROUND_UP: 进一法
    			   BigDecimal.ROUND_FLOOR:去尾法
    			   BigDecimal.ROUND_HALF_UP 四舍五入
    	*/
    	BigDecimal divide1 = big1.divide(big2,2,BigDecimal.ROUND_UP);
    	System.out.println(divide1); // 3.34
    	
    	BigDecimal divide2 = big1.divide(big2,2,BigDecimal.ROUND_FLOOR);
    	System.out.println(divide2);// 3.33
    
    	BigDecimal divide3 = big1.divide(big2,2,BigDecimal.ROUND_HALF_UP);
    	System.out.println(divide3);// 3.33

    }

ROUND_HALF_UP 与 ROUND_FLOOR区别

BigDecimal big1 = new BigDecimal("0.3");
BigDecimal big2 = new BigDecimal("4.0");

BigDecimal divide1 = big1.divide(big2,2,BigDecimal.ROUND_FLOOR);
System.out.println(divide1); // 0.07

BigDecimal divide2 = big1.divide(big2,2,BigDecimal.ROUND_HALF_UP);
System.out.println(divide2); // 0.08

ROUND_HALF_UP:保留小数位后一位如果满足5,就进一

ROUND_FLOOR:保留小数位后一位不管满足5还是不满足5直接舍去掉

8、日期时间类

8.1 Date类

8.1.1 Date类概述

java.util.Date类 表示特定的瞬间,精确到毫秒。

继续查阅Date类的描述,发现Date拥有多个构造函数,只是部分已经过时,但是其中有未过时的构造函数可以把毫秒值转成日期对象。

8.1.2 Date类的构造方法

方法名说明
public Date()分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)
public Date(long date)分配Date对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”, 即1970年1月1日00:00:00 GMT)以来的指定毫秒数。

由于我们处于东八区,所以我们的基准时间为1970年1月1日8时0分0秒。

public class Demo01Date {
    public static void main(String[] args) {
        // 创建日期对象,把当前的时间
        System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2018
        // 创建日期对象,把当前的毫秒值转成日期对象
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
    }
}

在使用println方法时,会自动调用Date类中的toString方法。Date类对Object类中的toString方法进行了覆盖重写,所以结果为指定格式的字符串。

8.1.3 Date类常用方法

Date类中的多数方法已经过时,常用的方法有

方法名说明
public long getTime()把日期对象转换成对应的时间毫秒值
public static void main(String[] args){
    Date date = new Date();
    // 获取从1970年到现在的毫秒值差
    long time = date.getTime();
    System.out.println(time);
}

8.2 DateFormat类

8.2.1 DateFormat类概述

java.text.DateFormat 是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换。

  • 格式化:按照指定的格式,从Date对象转换为String对象。

  • 解析:按照指定的格式,从String对象转换为Date对象。

8.2.2 DateFormat类的构造方法

由于DateFormat为抽象类,不能直接使用,所以需要常用的子类java.text.SimpleDateFormat。这个类需要一个模式(格式)来指定格式化或解析的标准。

方法名说明
public SimpleDateFormat()用默认的模式和默认语言环境的日期格式符号构造SimpleDateFormat。
public SimpleDateFormat(String pattern)用给定的模式和默认语言环境的日期格式符号构造SimpleDateFormat。

参数pattern是一个字符串,代表日期时间的自定义格式。

  • 常见的格式规则:
    标识字母(区分大小写)含义
    y
    M
    d
    H
    m
    s

  • 代码演示
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    
    public class Demo02SimpleDateFormat {
        public static void main(String[] args) {
            // 对应的日期格式如:2018-01-16 15:06:38
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }    
    }

8.2.3 DateFormat类的常用方法

方法名说明
public String format(Date date)将Date对象格式化为字符串。
public Date parse(String source)将字符串解析为Date对象。
  • 代码演示
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    /*
     把Date对象转换成String
    */
    public class Demo03DateFormatMethod {
        public static void main(String[] args) {
            // formatMethod();
            parseMethod();
        }
    
        public static void formatMethod(){
            Date date = new Date();
            // 创建日期格式化对象,在获取格式化对象时可以指定风格
            DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
            String str = df.format(date);
            System.out.println(str); // 2008年1月23日
        }
    
        public static void parseMethod(){
            DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
            String str = "2018年12月11日";
            Date date = df.parse(str);
            System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
        }
    }

8.2.4 SimpleDateFormat案例

  • 案例需求

    请使用日期时间相关的API,计算出一个人已经出生了多少天。

  • 案例分析
    1. 获取当前时间对应的毫秒值
    2. 获取自己出生日期对应的毫秒值
    3. 两个时间相减(当前时间– 出生日期)
  • 案例代码
    public static void function() throws Exception {
    	System.out.println("请输入出生日期 格式 YYYY-MM-dd");
    	// 获取出生日期,键盘输入
    	String birthdayString = new Scanner(System.in).next();
    	// 将字符串日期,转成Date对象
    	// 创建SimpleDateFormat对象,写日期模式
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	// 调用方法parse,字符串转成日期对象
    	Date birthdayDate = sdf.parse(birthdayString);	
    	// 获取今天的日期对象
    	Date todayDate = new Date();	
    	// 将两个日期转成毫秒值,Date类的方法getTime
    	long birthdaySecond = birthdayDate.getTime();
    	long todaySecond = todayDate.getTime();
    	long secone = todaySecond-birthdaySecond;	
    	if (secone < 0){
    		System.out.println("还没出生呢");
    	} else {
    		System.out.println(secone/1000/60/60/24);
    	}
    }

8.3 Calendar类

8.3.1 Calendar类概述

java.util.Calendar是日历类,在Date后出现,替换掉了许多Date的方法。该类将所有可能用到的时间信息封装为静态成员变量,方便获取。日历类就是方便获取各个时间属性的。

 

8.3.2 Calendar类获取方式

Calendar为抽象类,由于语言敏感性,Calendar类在创建对象时并非直接创建,而是通过静态方法创建,返回子类对象

方法名说明
public static Calendar getInstance()使用默认时区和语言环境获得一个日历
import java.util.Calendar;

public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

8.3.3 Calendar类常用方法

方法名说明
public int get(int field)返回给定日历字段的值。
public void set(int field, int value)将给定的日历字段设置为给定值。
public abstract void add(int field, int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量。
public Date getTime()返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象

Calendar类中提供很多成员常量,代表给定的日历字段:

字段值含义
YEAR
MONTH月(从0开始,可以+1使用)
DAY_OF_MONTH月中的天(几号)
HOUR时(12小时制)
HOUR_OF_DAY时(24小时制)
MINUTE
SECOND
DAY_OF_WEEK周中的天(周几,周日为1,可以-1使用)

  • 代码示例
    public class CalendarDemo {
        public static void main(String[] args) {
            // method1();
            // method2();
            // method3();
        }
    
        public static void method3(){
    
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            System.out.println(date); // Tue Jan 16 16:03:09 CST 2018
        }
    
        public static void method2(){
            Calendar cal = Calendar.getInstance();
            System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2018年1月17日
            // 使用add方法
            cal.add(Calendar.DAY_OF_MONTH, 2); // 加2天
            cal.add(Calendar.YEAR, -3); // 减3年
            System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2015年1月18日; 
        }
    
        public static void method1(){
            Calendar cal = Calendar.getInstance();
    
            // 设置年 
            int year = cal.get(Calendar.YEAR);
            // 设置月
            int month = cal.get(Calendar.MONTH) + 1;
            // 设置日
            int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
    
            System.out.print(year + "年" + month + "月" + dayOfMonth + "日");
    
            cal.set(Calendar.YEAR, 2020);
            System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2020年1月17日
        }
    }

    西方星期的开始为周日,中国为周一。 在Calendar类中,月份的表示是以0-11代表1-12月。日期是有大小关系的,时间靠后,时间越大。

常用字段
    * int year = cal.get(Calendar.YEAR);                  //当前年 
    * int month = (cal.get(Calendar.MONTH))+1;            //当前月 Calendar.MONTH从0开始     
    * int day_of_month = cal.get(Calendar.DAY_OF_MONTH);//当前月的第几天:即当前日 
    * int hour24 = cal.get(Calendar.HOUR_OF_DAY);        //当前时钟:HOUR_OF_DAY-24小时制     
    * int hour12 = cal.get(Calendar.HOUR);              //HOUR-12小时制   
    * int minute = cal.get(Calendar.MINUTE);              //当前:分钟   
    * int second = cal.get(Calendar.SECOND);              //当前秒   
    * int day_of_week = cal.get(Calendar.DAY_OF_WEEK)-1; // 星期几  Calendar.DAY_OF_WEEK用数字(1~7)表示(星期日~星期六)    
    * int ampm = cal.get(Calendar.AM_PM);                  //0-上午;1-下午  
    * int week_of_year = cal.get(Calendar.WEEK_OF_YEAR); //当前年的第几周      
    * int week_of_month = cal.get(Calendar.WEEK_OF_MONTH);//当前月的星期数  
    * int day_of_week_in_month = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);  //当前月中的第几个星期     
    * int day_of_year = cal.get(Calendar.DAY_OF_YEAR);       //当前年的第几天

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值