day11 StringBuilder&Math&Arrays&包装类&日期时间类

StringBuilder

StringBuilder类概述

String类是不可变的字符类,指的是地址。String s="hello"; s=s+"a",s是常量池,再增加拼接一个字符串a,还需要再次分配空间。

StringBuilder是一个可变的字符串类,我们可以把它看成是一个容器,这里的可变指的是 StringBuilder对象中的内容是可变的,也可称之为字符串缓冲类。

StringBuilder类的构造方法

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

代码演示

public class StringBuilderDemo01{
    public static void main(String[] args) {        
        StringBuilder sb = new StringBuilder();//16
        System.out.println(sb);//应该一个对象的地址值,一个空?
        System.out.println(sb.length());//0
        System.out.println(sb.capacity());//16
        System.out.println("-------------------------");
        // StringBuffer(int capacity)
        StringBuilder sb2 = new StringBuilder(4);//4
        System.out.println(sb2);
        System.out.println(sb2.length());   //0   有容量不一定有内容
        System.out.println(sb2.capacity());
        System.out.println("-------------------------");
        // StringBuffer(String str)
        StringBuilder sb3 = new StringBuilder("hello");
        System.out.println(sb3.length());//5 是内容的长度
        System.out.println(sb3.capacity());//5? 16? 5+16=21        
    }
}

StringBuilder类常见方法

添加方法

/*
 * StringBuffer的添加功能:
 * public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
 * public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();
        // 一步一步的添加数据
        // sb.append("hello");
        // sb.append(true);
        // sb.append(12);
        // sb.append(34.56);
        // 链式编程
        sb.append("hello").append(true).append(12).append(34.56);
        System.out.println("sb:" + sb);
        // public StringBuffer insert(int offset,String
        // str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
        sb.insert(5, "world");// helloworld
        System.out.println("sb:" + sb);
    }
}

删除方法

/*
 * StringBuffer的删除功能
 * public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
 * public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建对象
        StringBuffer sb = new StringBuffer();
        // 添加功能
        sb.append("hello").append("world").append("java");
        System.out.println("sb:" + sb);
        // public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
        // 需求:我要删除e这个字符,肿么办?
         sb.deleteCharAt(1);
        // public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
        // 需求:我要删除world这个字符串,肿么办? 包左不包右 从0开始数
         sb.delete(5, 10);//包左不包右
        // 需求:我要删除所有的数据
        sb.delete(0, sb.length());
        System.out.println("sb:" + sb);
    }
}

替换方法

/*
 * StringBuffer的替换功能:
 * public StringBuffer replace(int start,int end,String str):从start开始到end用str替换
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();
        // 添加数据
        sb.append("hello");
        sb.append("world");
        sb.append("java");
        System.out.println("sb:" + sb);
        // public StringBuffer replace(int start,int end,String str):从start开始到end用str替换
        // 需求:我要把world这个数据替换为"节日快乐"
        sb.replace(5, 10, "节日快乐");
        System.out.println("sb:" + sb);
    }
}

反转方法

/*
 * StringBuffer的反转功能:
 * public StringBuffer reverse()
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();
        // 添加数据
        sb.append("江小爱我");
        System.out.println("sb:" + sb);
        // public StringBuffer reverse()
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

转换方法

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

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 StringBufferTest {
        public static void main(String[] args) {
            // String -- StringBuffer
            String s = "hello";
            // 注意:不能把字符串的值直接赋值给StringBuffer
            // StringBuffer sb = "hello";//错误
            // StringBuffer sb = s;//错误
            // 方式1:通过构造方法
            StringBuffer sb = new StringBuffer(s);
            System.out.println("sb:" + sb);
    ​
            // 方式2:通过append()方法 String -- StringBuffer
            StringBuffer sb2 = new StringBuffer();
            sb2.append(s);
            System.out.println("sb2:" + sb2);
            System.out.println("---------------");
            // 方式1:通过构造方法 StringBuffer -- String
            StringBuffer buffer = new StringBuffer("java");
            String str = new String(buffer);
            System.out.println("str:" + str);
    ​
            // 方式2:通过toString()方法  StringBuffer -- String
            String str2 = buffer.toString();
            System.out.println("str2:" + str2);
        }
    }

StringBuilder,StringBuffer和String区别

面试用

StringBuilder 所有的方法和StringBuffer方法都一样,把我们上面的StringBuilder都可以改成StringBuffe常用
​
A: String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。
​
B: StringBuffer是同步的,数据安全,效率低.方法前关键字synchronized。
C: StringBuilder是不同步的,数据不安全,效率高,单线程;

StringBuilder案例 TODO

字符串拼接案例

  • 案例需求

    定义一个方法,把 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;
        }
    }

字符串反转案例

  • 案例需求

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

    例如,键盘录入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();
        }
    }

Math类

Math类概述

`java.lang.Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。类似这样的工具类,其所有方法均为静态方法,并且不会创建对象,调用起来非常简单。

3.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){
        System.out.println(Math.abs(-5));//取绝对值值为5
        System.out.println(Math.abs(5));//取绝对值值为5
​
        System.out.println(Math.ceil(3.3));//向上取整值为 4.0
        System.out.println(Math.ceil(-3.3));//向上取整值为 ‐3.0
        System.out.println(Math.ceil(5.1));//向上取整值为 6.0
​
        System.out.println(Math.floor(3.3));//向下取整值为3.0
        System.out.println(Math.floor(-3.3));//向下取整值为‐4.0
        System.out.println(Math.floor(5.1));//向下取整值为 5.0
​
        System.out.println(Math.round(5.5));//四舍五入值为6.0
        System.out.println(Math.round(5.4));//四舍五入值为5.0
    }
}

Arrays类

Arrays类概述

java.util.Arrays 此类包含用来操作数组的各种方法,比如排序和搜索等。其所有方法均为静态方法,调用起来非常简单。简单来说:Arrays这个是专门用来操作数组相关的工具类

Arrays类概述

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

代码演示

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]
    }
}

System类

System类概述

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

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

currentTimeMillis方法

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

import java.util.Date;
​
public class SystemDemo {
    public static void main(String[] args) {
        System.out.println("我们喜欢江一燕");
        System.exit(0);
        System.out.println("我们也喜欢梅老师");
​
        System.out.println(System.currentTimeMillis());
​
        // 单独得到这样的实际目前对我们来说意义不大
        // 那么,它到底有什么作用呢?
        // 要求:请大家给我统计这段程序的运行时间
        long start = System.currentTimeMillis();
        for (int x = 0; x < 100000; x++) {
            System.out.println("hello" + x);
        }
        long end = System.currentTimeMillis();
        System.out.println("共耗时:" + (end - start) + "毫秒");
    }
}

arraycopy方法

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

参数序号参数名称参数类型参数含义
1srcObject源数组
2srcPosint源数组索引起始位置
3destObject目标数组
4destPosint目标数组索引起始位置
5lengthint复制元素个数
  • 代码实现
    public class Demo11SystemArrayCopy {
        public static void main(String[] args) {
            // 定义数组
            int[] arr = { 11, 22, 33, 44, 55 };
            int[] arr2 = { 6, 7, 8, 9, 10 };
            // 请大家看这个代码的意思,从arr 1位置开始复制到arr2中2个长度
            System.arraycopy(arr, 1, arr2, 2, 2);
    ​
            System.out.println(Arrays.toString(arr));
            System.out.println(Arrays.toString(arr2));//6,7,22,33,10
        }
    }

包装类

包装类概述

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

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

装箱与拆箱

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

  • 什么是装箱:

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

  • 什么是拆箱:

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

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

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

自动装箱与自动拆箱

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

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

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

  • 基本类型 ---> String
    //基本类型 --> String
    int i = 10;
    //拼接方式
    String s = i +"";
    ​
    //静态toString(参数)方法
    String s =  Integer.toString(10);
    ​
    //静态方法valueOf(参数), valueOf()这个方法可以把任意的基本类型转成String类型
    String s = String.valueOf(20);
  • String ---> 基本类型

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

    public class Demo18WrapperParse {
        public static void main(String[] args) {
            //字符串 --> int 
            String i = "100";
            int num = Integer.parseInt(i); 
            double v = Double.parseDouble("3.34");
            float v1 = Float.parseFloat("3.3");
            //...所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型
        }
    }

    除了Character类之外,其他所有包装类都具有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异常。

    Integer 和 int 有什么区别?

    Integer 和 int 有什么区别?
    ​
    Int 是基本数据类型, Integer是int的包装类
    Int 默认值为0   , Integer的默认值null
    ​
    或者什么情况下使用Integer, Int?
    举例:小明考试,最终得到0分,请问他是去考试还是没去考试?去考试  用int
          小明考试,最终null,请问他是去考试还是没去考试?没有考试  用Integer

BigInteger类

BigInteger类概述

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

BigInteger类的构造方法

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

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

BigInteger类的四则运算演示

public class BigIntegerDemo{
    public static void main(String[] args) {
        //大数据封装为BigInteger对象 ,int max=2147483647 long 9223372036854774807
        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);
    }
}

BigDecimal类

BigDecimal类的引入

  • 在程序中执行下列代码,会出现什么问题?
  • 0.2+0.1

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类可以实现浮点数据的高精度运算。

BigDecimal类的构造方法

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

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

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.075  0.07 不管后面有没有满足5直接舍掉
​
        BigDecimal divide2 = big1.divide(big2,2,BigDecimal.ROUND_HALF_UP);//四舍五入
        System.out.println(divide2); //0.075  0.08 满5就进1

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

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

日期时间类

Date类

Date类概述

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

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

Date类的构造方法

方法名说明
public Date()分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)
public Date(long date)分配Date对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,<br />即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方法进行了覆盖重写,所以结果为指定格式的字符串。

Date类常用方法

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

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

DateFormat类

DateFormat类概述

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

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

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

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");
        }    
    }

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) throws ParseException {
            // Date --> String
            Date d = new Date();
            // 创建格式化对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);      
            
            //String --> Date
            String str = "2019-08-08 12:12:12";
            //在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(str);
            System.out.println(dd);
        }
    }

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 sdf = new SimpleDateFormat("yyyy-MM-dd");    
        // 调用方法parse,字符串转成日期对象
        Date birthdayDate = sdf.parse(birthdayString);      
        // 获取今天的日期对象
        Date todayDate = new Date();        
        // 出生日期
        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);
        }
    }

Calendar类

Calendar类概述

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

 

Calendar类获取方式

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

方法名说明
public static Calendar getInstance()使用默认时区和语言环境获得一个日历
import java.util.Calendar;
public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

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 method4(){
             Calendar cal2 = Calendar.getInstance();
            //获取当前日期
            int year = cal2.get(Calendar.YEAR);
            int month = cal2.get(Calendar.MONTH)+1;
            int day = cal2.get(Calendar.DAY_OF_MONTH);
            System.out.println(year+"年"+month+"月"+day+"日");//2021年10月26日
            
            System.out.println("----------------");
    ​
            //修改日期
            cal2.add(Calendar.DAY_OF_MONTH,2);//加2天
            cal2.add(Calendar.YEAR,-2);//减2年
            //修改后重新获取
            int year2 = cal2.get(Calendar.YEAR);
            int month2 = cal2.get(Calendar.MONTH)+1;
            int day2 = cal2.get(Calendar.DAY_OF_MONTH);
            
            System.out.println(year2+"年"+month2+"月"+day2+"日");//2019年10月28日
        }
    ​
        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();
            //设置时间
            // cal.set(Calendar.YEAR, 2021);
            // cal.set(Calendar.MONTH, 11);
            // cal.set(Calendar.DAY_OF_MONTH, 26);
    ​
            //设置时间
            cal.set(2021,7,24,13,00,00);
    ​
            //格式化
            Date d = cal.getTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String s = simpleDateFormat.format(d);
            System.out.println(s);
        }
    ​
        public static void method1(){
             // 使用默认时区和语言环境获得一个日历
            Calendar cal = Calendar.getInstance();
    ​
            // 赋值时年月日时分秒常用的6个值,注意月份下标从0开始,所以取月份要+1
            System.out.println("年:" + cal.get(Calendar.YEAR));
            System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));
            System.out.println("日:" + cal.get(Calendar.DAY_OF_MONTH));
            System.out.println("时:" + cal.get(Calendar.HOUR_OF_DAY));
            System.out.println("分:" + cal.get(Calendar.MINUTE));
            System.out.println("秒:" + cal.get(Calendar.SECOND));
        }
    }

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

Calendar和Date互转

//Calendar转Date
Calendar c = Calendar.getInstance();
Date d = c.getTime();
​
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s = simpleDateFormat.format(d);
System.out.println("Calendar转Date为:"+s);
//Date转Calendar
//创建日期对象
Date d = new Date();
        
//创建日历对象
Calendar c = Calendar.getInstance();
c.setTime(d);
        
System.out.println(c.get(Calendar.YEAR) +"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DATE));
​

Date和Calendar有什么区别

区别:比较明显的区别是Date是日期,Calendar是日历,Date是类,Calendar是抽象类。当然,你也可以觉得Calendar是Date的加强版,今后如何使用呢? 都会使用,Calendar功能更强大

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值