Java进阶(上)
Java进阶(上)
java常用类
包装类
-
包装类的分类
-
针对八种基本数据类型相应的应用类型--包装类
-
有了类的特点,就可以调用类中的方法
![]()
-
装箱和拆箱
- 装箱:基本类型 -> 包装类型
- 拆箱:包装类型 -> 基本类型
- jdk5之前是手动装箱和拆箱
- 自动装箱底层使用的是Integer.valueOf()方法,自动拆箱使用的是intValue()方法
手动装箱
// 手动装箱
int i = 10;
Integer integer = new Integer(i);
手动拆箱
// 手动拆箱
int i1 = integer.intValue();
自动装箱
// 自动装箱
int i2 = 100;
Integer integer2 = i2;
自动拆箱
// 自动拆箱
int i3 = integer2;
包装类和String类型互相转换

String类
- String类用于保存字符串
- 字符串的字符使用的是Unicod字符编码,一个字符串不区分汉字和英文占两个字节
- String类常用的构造方法
String s1 = new String();
String s2 = new String("hello, world");
String s3 = new String(a);
String常用方法
-
- equals(Object anObject):内容比较,区分大小写。
-
- equalsIgnoreCase(String anotherString):内容比较,忽略大小写。
-
- length():返回字符数。
-
- indexOf(int ch)/indexOf(String str):返回第一个匹配的索引。
-
- lastIndexOf(...):返回最后一个匹配的索引。
-
- substring(int beginIndex, int endIndex):截取子串,endIndex可选。
-
- trim():去除前后空格。
-
- charAt(int index):返回指定位置的字符。
-
- toUpperCase()/toLowerCase():转换大小写。
-
- concat(String str):连接字符串。
-
- compareTo(String anotherString):字典顺序比较。
-
- toCharArray():转为字符数组。
-
format(String format, Object... args):格式化字符串。
StringBuffer类
-
很多方法和String类相同,但是StringBuffer可以改变长度
-
StringBuffer是一个容器
-
因为StringBuffer 字符内容是存在 char[]value,所以在变化的时侯不用每次都更换地址
StringBuffer构造器

String转StringBuffer
String str1 = "Hello World";
// 1. 使用构造器
StringBuffer stringBuffer = new StringBuffer(str1);
StringBuffer stringBuffer1 = new StringBuffer();
// 2.使用append()方法
stringBuffer1 = stringBuffer1.append(str1);
StringBuffer转String
String str1 = "Hello World";
// 1. toString方法
StringBuffer stringBuffer = new StringBuffer(str1);
str1 = stringBuffer.toString();
// 2. 使用构造函数
String s = new String(stringBuffer);
StringBuffer常用方法
- 构造方法
-
StringBuffer():创建一个空的StringBuffer对象。StringBuffer sb = new StringBuffer(); -
StringBuffer(String str):根据指定的字符串创建一个StringBuffer对象。StringBuffer sb = new StringBuffer("Hello");
- 字符串拼接
-
append(String str):将指定的字符串追加到当前StringBuffer的末尾。StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb.toString()); // 输出:Hello World -
insert(int offset, String str):将指定的字符串插入到当前StringBuffer的指定位置。StringBuffer sb = new StringBuffer("Hello"); sb.insert(3, " World"); System.out.println(sb.toString()); // 输出:Hel Worldlo
- 字符串替换
-
replace(int start, int end, String str):用指定的字符串替换当前StringBuffer中从start到end(不包括end)的子字符串。StringBuffer sb = new StringBuffer("Hello World"); sb.replace(6, 11, "Java"); System.out.println(sb.toString()); // 输出:Hello Java
- 字符串删除
-
delete(int start, int end):删除当前StringBuffer中从start到end(不包括end)的子字符串。StringBuffer sb = new StringBuffer("Hello World"); sb.delete(6, 11); System.out.println(sb.toString()); // 输出:Hello -
deleteCharAt(int index):删除指定索引处的字符。StringBuffer sb = new StringBuffer("Hello"); sb.deleteCharAt(2); System.out.println(sb.toString()); // 输出:Helo
- 字符串反转
-
reverse():反转当前StringBuffer中的字符。StringBuffer sb = new StringBuffer("Hello"); sb.reverse(); System.out.println(sb.toString()); // 输出:olleH
- 字符串查找
-
indexOf(String str):返回指定字符串在当前StringBuffer中第一次出现的索引。StringBuffer sb = new StringBuffer("Hello World"); int index = sb.indexOf("World"); System.out.println(index); // 输出:6 -
lastIndexOf(String str):返回指定字符串在当前StringBuffer中最后一次出现的索引。StringBuffer sb = new StringBuffer("Hello World World"); int index = sb.lastIndexOf("World"); System.out.println(index); // 输出:12
- 字符串长度
-
length():返回当前StringBuffer的长度。StringBuffer sb = new StringBuffer("Hello"); int length = sb.length(); System.out.println(length); // 输出:5
- 字符串容量
-
capacity():返回当前StringBuffer的容量。StringBuffer sb = new StringBuffer("Hello"); int capacity = sb.capacity(); System.out.println(capacity); // 输出:16(默认初始容量为16) -
ensureCapacity(int minimumCapacity):确保当前StringBuffer的容量至少为指定值。StringBuffer sb = new StringBuffer("Hello"); sb.ensureCapacity(20); int capacity = sb.capacity(); System.out.println(capacity); // 输出:20
- 字符串转换
-
toString():将当前StringBuffer转换为字符串。StringBuffer sb = new StringBuffer("Hello"); String str = sb.toString(); System.out.println(str); // 输出:Hello
- 字符操作
-
charAt(int index):返回指定索引处的字符。StringBuffer sb = new StringBuffer("Hello"); char ch = sb.charAt(2); System.out.println(ch); // 输出:l -
setCharAt(int index, char ch):设置指定索引处的字符。StringBuffer sb = new StringBuffer("Hello"); sb.setCharAt(2, 'a'); System.out.println(sb.toString()); // 输出:Healo
- 子字符串
-
substring(int start, int end):返回从start到end(不包括end)的子字符串。StringBuffer sb = new StringBuffer("Hello World"); String sub = sb.substring(6, 11); System.out.println(sub); // 输出:World
StringBuilber类
- 它与
StringBuffer类似,但不保证线程安全,因此在单线程环境中性能更高
StringBuilber类常用方法
1. **构造方法**
-
StringBuilder():创建一个空的StringBuilder对象。StringBuilder sb = new StringBuilder(); -
StringBuilder(String str):根据指定的字符串创建一个StringBuilder对象。StringBuilder sb = new StringBuilder("Hello");
- 字符串拼接
-
append(String str):将指定的字符串追加到当前StringBuilder的末尾。StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb.toString()); // 输出:Hello World -
append(Object obj):将任意对象的字符串表示形式追加到当前StringBuilder的末尾。StringBuilder sb = new StringBuilder("Hello"); sb.append(123); System.out.println(sb.toString()); // 输出:Hello123 -
insert(int offset, String str):将指定的字符串插入到当前StringBuilder的指定位置。StringBuilder sb = new StringBuilder("Hello"); sb.insert(3, " World"); System.out.println(sb.toString()); // 输出:Hel Worldlo
- 字符串替换
-
replace(int start, int end, String str):用指定的字符串替换当前StringBuilder中从start到end(不包括end)的子字符串。StringBuilder sb = new StringBuilder("Hello World"); sb.replace(6, 11, "Java"); System.out.println(sb.toString()); // 输出:Hello Java
- 字符串删除
-
delete(int start, int end):删除当前StringBuilder中从start到end(不包括end)的子字符串。StringBuilder sb = new StringBuilder("Hello World"); sb.delete(6, 11); System.out.println(sb.toString()); // 输出:Hello -
deleteCharAt(int index):删除指定索引处的字符。StringBuilder sb = new StringBuilder("Hello"); sb.deleteCharAt(2); System.out.println(sb.toString()); // 输出:Helo
- 字符串反转
-
reverse():反转当前StringBuilder中的字符。StringBuilder sb = new StringBuilder("Hello"); sb.reverse(); System.out.println(sb.toString()); // 输出:olleH
- 字符串查找
-
indexOf(String str):返回指定字符串在当前StringBuilder中第一次出现的索引。StringBuilder sb = new StringBuilder("Hello World"); int index = sb.indexOf("World"); System.out.println(index); // 输出:6 -
lastIndexOf(String str):返回指定字符串在当前StringBuilder中最后一次出现的索引。StringBuilder sb = new StringBuilder("Hello World World"); int index = sb.lastIndexOf("World"); System.out.println(index); // 输出:12
- 字符串长度
-
length():返回当前StringBuilder的长度。StringBuilder sb = new StringBuilder("Hello"); int length = sb.length(); System.out.println(length); // 输出:5
- 字符串容量
-
capacity():返回当前StringBuilder的容量。StringBuilder sb = new StringBuilder("Hello"); int capacity = sb.capacity(); System.out.println(capacity); // 输出:16(默认初始容量为16) -
ensureCapacity(int minimumCapacity):确保当前StringBuilder的容量至少为指定值。StringBuilder sb = new StringBuilder("Hello"); sb.ensureCapacity(20); int capacity = sb.capacity(); System.out.println(capacity); // 输出:20
- 字符串转换
-
toString():将当前StringBuilder转换为字符串。StringBuilder sb = new StringBuilder("Hello"); String str = sb.toString(); System.out.println(str); // 输出:Hello
- 字符操作
-
charAt(int index):返回指定索引处的字符。StringBuilder sb = new StringBuilder("Hello"); char ch = sb.charAt(2); System.out.println(ch); // 输出:l -
setCharAt(int index, char ch):设置指定索引处的字符。StringBuilder sb = new StringBuilder("Hello"); sb.setCharAt(2, 'a'); System.out.println(sb.toString()); // 输出:Healo
- 子字符串
-
substring(int start, int end):返回从start到end(不包括end)的子字符串。StringBuilder sb = new StringBuilder("Hello World"); String sub = sb.substring(6, 11); System.out.println(sub); // 输出:World
注意事项
- 线程安全:
StringBuilder是非线程安全的,适合在单线程环境中使用。- 如果需要线程安全的字符串操作,可以使用
StringBuffer。
- 性能:
StringBuilder的性能比StringBuffer高,因为它不涉及同步机制。- 在单线程环境中,推荐使用
StringBuilder。
- 容量管理:
- 默认初始容量为16,当字符串长度超过容量时,会自动扩容。
- 可以通过
ensureCapacity方法提前设置容量,避免多次扩容带来的性能开销。
Math类 (数学运算类)
- Math类包含用于执行基本数学运算方法
Math类常见方法
1. 基本数学常量
-
Math.PI:表示圆周率 π,约等于 3.14159。double pi = Math.PI; System.out.println(pi); // 输出:3.141592653589793 -
Math.E:表示自然对数的底数 e,约等于 2.71828。double e = Math.E; System.out.println(e); // 输出:2.718281828459045
2. 基本数学运算
-
Math.abs(double a):返回参数的绝对值。double absValue = Math.abs(-10.5); System.out.println(absValue); // 输出:10.5 -
Math.max(double a, double b):返回两个参数中的较大值。double maxValue = Math.max(5.5, 7.2); System.out.println(maxValue); // 输出:7.2 -
Math.min(double a, double b):返回两个参数中的较小值。double minValue = Math.min(5.5, 7.2); System.out.println(minValue); // 输出:5.5
3. 四舍五入
-
Math.round(double a):返回最接近参数的整数。long roundedValue = Math.round(5.5); System.out.println(roundedValue); // 输出:6 -
Math.ceil(double a):返回大于或等于参数的最小整数。double ceilValue = Math.ceil(5.5); System.out.println(ceilValue); // 输出:6.0 -
Math.floor(double a):返回小于或等于参数的最大整数。double floorValue = Math.floor(5.5); System.out.println(floorValue); // 输出:5.0
4. 随机数
-
Math.random():返回一个随机的double值,范围在 0.0(包含)到 1.0(不包含)之间。double randomValue = Math.random(); System.out.println(randomValue); // 输出:例如 0.8456234
5. 三角函数
-
Math.sin(double a):返回参数的正弦值。double sinValue = Math.sin(Math.PI / 2); // sin(90度) System.out.println(sinValue); // 输出:1.0 -
Math.cos(double a):返回参数的余弦值。double cosValue = Math.cos(0); // cos(0度) System.out.println(cosValue); // 输出:1.0 -
Math.tan(double a):返回参数的正切值。double tanValue = Math.tan(Math.PI / 4); // tan(45度) System.out.println(tanValue); // 输出:1.0
6. 对数和指数
-
Math.log(double a):返回参数的自然对数值(以 e 为底)。double logValue = Math.log(Math.E); System.out.println(logValue); // 输出:1.0 -
Math.log10(double a):返回参数的常用对数值(以 10 为底)。double log10Value = Math.log10(100); System.out.println(log10Value); // 输出:2.0 -
Math.exp(double a):返回 e 的参数次幂。double expValue = Math.exp(1); System.out.println(expValue); // 输出:2.718281828459045
7. 幂运算
-
Math.pow(double a, double b):返回 a 的 b 次幂。double powValue = Math.pow(2, 3); System.out.println(powValue); // 输出:8.0
8. 平方根和立方根
-
Math.sqrt(double a):返回参数的平方根。double sqrtValue = Math.sqrt(16); System.out.println(sqrtValue); // 输出:4.0 -
Math.cbrt(double a):返回参数的立方根。double cbrtValue = Math.cbrt(27); System.out.println(cbrtValue); // 输出:3.0
9. 角度转换
-
Math.toRadians(double angdeg):将角度转换为弧度。double radians = Math.toRadians(90); System.out.println(radians); // 输出:1.5707963267948966 -
Math.toDegrees(double angrad):将弧度转换为角度。double degrees = Math.toDegrees(Math.PI / 2); System.out.println(degrees); // 输出:90.0
练习
取a-b之间的随机整数
// Math.random() * x 会返回0到小于x的小数
public int random(int min, int max) {
return (int)(Math.random() * (max - min + 1) + min);
}
Arrays类 (数组类)
- arrays类用于管理操作数组
Arrays类常见方法
1. 排序
-
sort():对数组进行排序。默认使用自然排序(升序),也可以通过传入自定义的比较器来实现自定义排序。int[] arr = {5, 2, 9, 1, 5, 6}; Arrays.sort(arr); // 升序排序 System.out.println(Arrays.toString(arr)); // 输出:[1, 2, 5, 5, 6, 9]
2. 搜索
-
binarySearch():在已排序的数组中使用二分查找法查找指定元素。返回元素的索引,如果未找到则返回负值。int[] arr = {1, 2, 5, 5, 6, 9}; int index = Arrays.binarySearch(arr, 5); System.out.println(index); // 输出:2(或3,因为5有两个)
3. 转换为字符串
-
toString():将数组转换为字符串形式,方便打印和调试。int[] arr = {1, 2, 3}; System.out.println(Arrays.toString(arr)); // 输出:[1, 2, 3]
4. 深度转换为字符串
-
deepToString():用于多维数组的字符串表示。int[][] arr = {{1, 2}, {3, 4}}; System.out.println(Arrays.deepToString(arr)); // 输出:[[1, 2], [3, 4]]
5. 填充数组
-
fill():用指定的值填充数组。int[] arr = new int[5]; Arrays.fill(arr, 10); System.out.println(Arrays.toString(arr)); // 输出:[10, 10, 10, 10, 10]
6. 比较数组
-
equals():比较两个数组是否相等。int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; System.out.println(Arrays.equals(arr1, arr2)); // 输出:true
7. 深度比较数组
-
deepEquals():比较多维数组是否相等。int[][] arr1 = {{1, 2}, {3, 4}}; int[][] arr2 = {{1, 2}, {3, 4}}; System.out.println(Arrays.deepEquals(arr1, arr2)); // 输出:true
8. 复制数组
-
copyOf():复制数组的一部分或全部。int[] arr = {1, 2, 3, 4, 5}; int[] copy = Arrays.copyOf(arr, 3); // 复制前3个元素 System.out.println(Arrays.toString(copy)); // 输出:[1, 2, 3]
9. 复制数组的一部分
-
copyOfRange():复制数组的指定范围。int[] arr = {1, 2, 3, 4, 5}; int[] subArray = Arrays.copyOfRange(arr, 1, 4); // 从索引1到3 System.out.println(Arrays.toString(subArray)); // 输出:[2, 3, 4]
System类 (系统类)
System类是一个非常重要的工具类,它提供了与系统相关的属性和方法,用于执行一些基础的系统操作。System类位于java.lang包中,因此在使用时不需要导入任何包
1. 系统属性
System 类提供了访问系统属性的方法,这些属性是关于运行环境的键值对信息。
-
getProperty(String key):获取指定键的系统属性值。String javaVersion = System.getProperty("java.version"); System.out.println("Java Version: " + javaVersion); String osName = System.getProperty("os.name"); System.out.println("OS Name: " + osName); -
setProperties(Properties props):设置系统属性。Properties props = System.getProperties(); props.setProperty("my.custom.property", "value"); System.setProperties(props);
2. 输入输出流
System 类提供了三个标准的输入输出流:
System.in:标准输入流,通常对应键盘输入。System.out:标准输出流,通常对应屏幕输出。System.err:标准错误输出流,通常也对应屏幕输出,但用于输出错误信息。
这些流的类型分别是 InputStream 和 PrintStream。
示例:重定向输出
PrintStream originalOut = System.out;
PrintStream fileOut = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(fileOut); // 将标准输出重定向到文件
System.out.println("This will be written to output.txt");
System.setOut(originalOut); // 恢复标准输出
System.out.println("This will be printed to the console");
3. 时间相关方法
-
currentTimeMillis():返回当前时间的毫秒值(自1970年1月1日00:00:00 GMT以来的毫秒数)。long startTime = System.currentTimeMillis(); // 执行一些操作 long endTime = System.currentTimeMillis(); System.out.println("Elapsed Time: " + (endTime - startTime) + " ms"); -
nanoTime():返回当前时间的纳秒值,用于高精度的时间测量。long startNano = System.nanoTime(); // 执行一些操作 long endNano = System.nanoTime(); System.out.println("Elapsed Time: " + (endNano - startNano) + " ns");
4. 系统操作
-
exit(int status):终止当前运行的Java虚拟机。status为0表示正常退出,非0表示异常退出。System.out.println("Program is exiting..."); System.exit(0); -
gc():请求垃圾回收器运行。虽然不能强制执行垃圾回收,但可以建议JVM进行垃圾回收。System.gc();
5. 环境变量
-
getenv():获取系统的环境变量。Map<String, String> env = System.getenv(); String path = env.get("PATH"); System.out.println("PATH: " + path);
注意事项
System类中的方法大多是静态方法,可以直接通过类名调用。- 使用
System.exit()时需要谨慎,因为它会终止整个程序,包括所有线程。 System.gc()并不能保证立即触发垃圾回收,它只是向JVM发出请求。
BigInteger 类(任意精度整数的类)
-
在Java中,
BigInteger是一个用于表示任意精度整数的类。它提供了对非常大的整数进行精确计算的能力,这些整数的大小超出了基本数据类型int和long的范围。BigInteger是不可变的(immutable),并且提供了丰富的数学运算方法。 -
BigInteger
类位于java.math包中,因此在使用时需要导入java.math.BigInteger`。
1. 创建 BigInteger 对象
BigInteger 提供了多种构造方法和工厂方法来创建对象。
1.1 使用字符串创建
BigInteger bigInt1 = new BigInteger("123456789012345678901234567890");
System.out.println(bigInt1); // 输出:123456789012345678901234567890
1.2 使用字节数组创建
byte[] byteArray = {1, 2, 3, 4};
BigInteger bigInt2 = new BigInteger(1, byteArray); // 正数
System.out.println(bigInt2); // 输出:67305985
1.3 使用 valueOf 方法
BigInteger bigInt3 = BigInteger.valueOf(1234567890L); // 从 long 创建
System.out.println(bigInt3); // 输出:1234567890
2. 常用方法
BigInteger 提供了丰富的数学运算方法,包括加法、减法、乘法、除法、取模等。
2.1 基本运算
-
加法
BigInteger a = new BigInteger("100"); BigInteger b = new BigInteger("200"); BigInteger sum = a.add(b); System.out.println(sum); // 输出:300 -
减法
BigInteger diff = a.subtract(b); System.out.println(diff); // 输出:-100 -
乘法
BigInteger product = a.multiply(b); System.out.println(product); // 输出:20000 -
除法
BigInteger quotient = b.divide(a); System.out.println(quotient); // 输出:2 -
取模
BigInteger remainder = b.mod(a); System.out.println(remainder); // 输出:0
2.2 比较
-
比较大小
int comparison = a.compareTo(b); System.out.println(comparison); // 输出:-1(a < b) -
等于
boolean isEqual = a.equals(b); System.out.println(isEqual); // 输出:false
2.3 进制转换
-
从字符串创建(指定进制)
BigInteger hex = new BigInteger("1A", 16); // 十六进制 System.out.println(hex); // 输出:26 -
转换为其他进制字符串
String hexString = hex.toString(16); // 转换为十六进制字符串 System.out.println(hexString); // 输出:1a
2.4 其他数学运算
-
幂运算
BigInteger power = a.pow(3); // a 的 3 次方 System.out.println(power); // 输出:1000000 -
最大公约数
BigInteger gcd = a.gcd(b); System.out.println(gcd); // 输出:100 -
模幂运算
BigInteger modPow = a.modPow(new BigInteger("3"), new BigInteger("1000")); System.out.println(modPow); // 输出:100
3. 注意事项
3.1 性能问题
BigInteger的运算比基本数据类型慢得多,因为它需要处理任意精度的整数。因此,如果不需要高精度计算,建议使用基本数据类型(如int或long)。
3.2 除法和取模
- 在使用
divide和mod方法时,需要确保除数不为零,否则会抛出ArithmeticException。
3.3 不可变性
BigInteger是不可变的,所有数学运算都会返回一个新的BigInteger对象,而不是修改原有对象。
BigDecimal 类(高精度浮点数类)
BigDecimal 是 Java 中用于高精度浮点数运算的类,特别适用于金融、货币计算等对精度要求极高的场景。它提供了精确的定点数运算,避免了传统浮点类型(如 float 和 double)可能导致的精度问题。
1. 构造方法
BigDecimal 提供了多种构造方法,但推荐使用字符串构造方法来避免精度问题:
BigDecimal bd1 = new BigDecimal("123.456");
其他构造方法包括:
-
从
double构造(不推荐,可能引入精度问题):BigDecimal bd2 = new BigDecimal(123.456); -
从
long或int构造:BigDecimal bd3 = BigDecimal.valueOf(1234567890L); -
从
BigInteger构造:BigInteger bi = new BigInteger("123456789"); BigDecimal bd4 = new BigDecimal(bi);
2. 常用方法
2.1 基本运算
-
加法:
BigDecimal a = new BigDecimal("10.5"); BigDecimal b = new BigDecimal("2.5"); BigDecimal sum = a.add(b); // 结果为 13.0 -
减法:
BigDecimal diff = a.subtract(b); // 结果为 8.0 -
乘法:
BigDecimal product = a.multiply(b); // 结果为 21.0 -
除法:
BigDecimal quotient = a.divide(b, 2, RoundingMode.HALF_UP); // 结果为 4.20
2.2 舍入与小数位数
-
设置小数位数和舍入模式:
BigDecimal value = new BigDecimal("123.456789"); BigDecimal rounded = value.setScale(2, RoundingMode.HALF_UP); // 结果为 123.46
2.3 比较
-
比较大小:
int comparison = a.compareTo(b); // 返回 -1(a < b)、0(a == b)或 1(a > b)
2.4 其他方法
-
取绝对值:
BigDecimal absValue = a.abs(); // 返回绝对值 -
取相反数:
BigDecimal negValue = a.negate(); // 返回相反数 -
去掉末尾零:
BigDecimal stripped = value.stripTrailingZeros(); // 去掉末尾的零
3. 舍入模式
BigDecimal 提供了多种舍入模式:
RoundingMode.HALF_UP:四舍五入(最常用)。RoundingMode.HALF_DOWN:五舍六入。RoundingMode.UP:向远离零的方向舍入。RoundingMode.DOWN:向零方向舍入。
4. 使用注意事项
- 避免使用
double构造:直接使用double构造可能会引入精度问题,推荐使用字符串构造。 - 性能问题:
BigDecimal的运算比基本数据类型慢,适用于需要高精度的场景。
Date 时间类
1. java.util.Date
java.util.Date 是Java早期的日期类,用于表示日期和时间。它是一个比较古老的类,存在一些设计上的不足,例如线程不安全、缺乏时区支持等。
1.1 创建 Date 对象
Date now = new Date(); // 获取当前日期和时间
System.out.println(now); // 输出:Fri Feb 09 14:30:00 CST 2024
1.2 格式化和解析
Date 类本身不支持格式化和解析,需要借助 SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now); // 格式化为字符串
System.out.println(formattedDate); // 输出:2024-02-09 14:30:00
Date parsedDate = sdf.parse("2024-02-09 14:30:00"); // 从字符串解析为 Date
System.out.println(parsedDate); // 输出:Fri Feb 09 14:30:00 CST 2024
Time (时间类)
java.time 是 Java 8 及以上版本中引入的全新日期和时间 API,旨在解决旧的日期时间类(如 java.util.Date 和 java.util.Calendar)存在的诸多问题,例如线程不安全、设计复杂、易用性差等。java.time 包中的类是不可变的、线程安全的,并且提供了更清晰、更强大的日期和时间操作功能。
以下是 java.time 包中一些核心类的介绍和使用示例:
1. LocalDate
LocalDate 表示不带时间的日期(如2025-02-07),只包含年、月、日信息。
常用方法
-
获取当前日期:
LocalDate today = LocalDate.now(); System.out.println("今天的日期: " + today); -
获取特定日期:
LocalDate specificDate = LocalDate.of(2025, 2, 7);
System.out.println("特定日期: " + specificDate);
- **日期加减**:
```java
LocalDate tomorrow = today.plusDays(1);
LocalDate yesterday = today.minusDays(1);
System.out.println("明天的日期: " + tomorrow);
System.out.println("昨天的日期: " + yesterday);
-
日期比较:
boolean isBefore = today.isBefore(tomorrow);
System.out.println("今天是否在明天之前: " + isBefore);
#### **2. `LocalTime`**
`LocalTime` 表示不带日期的时间(如12:34:56),只包含小时、分钟、秒和纳秒信息。
##### **常用方法**
- **获取当前时间**:
```java
LocalTime now = LocalTime.now();
System.out.println("当前时间: " + now);
-
获取特定时间:
LocalTime specificTime = LocalTime.of(12, 34, 56); System.out.println("特定时间: " + specificTime); -
时间加减:
LocalTime later = now.plusHours(2).plusMinutes(30); LocalTime earlier = now.minusHours(1); System.out.println("2小时30分钟后的当前时间: " + later); System.out.println("1小时前的当前时间: " + earlier);
3. LocalDateTime
LocalDateTime 是 LocalDate 和 LocalTime 的组合,表示日期和时间的组合(如2025-02-07T12:34:56),但不包含时区信息。
常用方法
-
获取当前日期和时间:
LocalDateTime now = LocalDateTime.now(); System.out.println("当前日期和时间: " + now); -
获取特定日期和时间:
LocalDateTime specificDateTime = LocalDateTime.of(2025, 2, 7, 12, 34, 56); System.out.println("特定日期和时间: " + specificDateTime); -
日期时间加减:
LocalDateTime later = now.plusDays(1).plusHours(2); LocalDateTime earlier = now.minusDays(1).minusMinutes(30); System.out.println("1天2小时后的当前日期和时间: " + later); System.out.println("1天30分钟前的当前日期和时间: " + earlier);
4. ZonedDateTime
ZonedDateTime 是带时区的日期时间类,它结合了日期、时间和时区信息,适用于处理与时区相关的场景。
常用方法
-
获取当前带时区的日期时间:
ZonedDateTime now = ZonedDateTime.now(); System.out.println("当前带时区的日期时间: " + now); -
指定时区:
ZonedDateTime shanghaiTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai")); System.out.println("上海时间: " + shanghaiTime); -
时区转换:
ZonedDateTime utcTime = now.withZoneSameInstant(ZoneId.of("UTC")); System.out.println("UTC时间: " + utcTime);
5. Duration 和 Period
Duration 和 Period 用于表示时间间隔。
Duration
-
表示两个时间点之间的时间差,以秒和纳秒为单位。
-
示例:
LocalDateTime start = LocalDateTime.of(2025, 2, 7, 12, 0); LocalDateTime end = LocalDateTime.of(2025, 2, 7, 14, 30); Duration duration = Duration.between(start, end); System.out.println("时间差: " + duration.toHours() + "小时" + duration.toMinutesPart() + "分钟");
Period
-
表示两个日期之间的差异,以年、月、日为单位。
-
示例:
LocalDate date1 = LocalDate.of(2025, 1, 1); LocalDate date2 = LocalDate.of(2025, 12, 31); Period period = Period.between(date1, date2); System.out.println("日期差: " + period.getYears() + "年" + period.getMonths() + "月" + period.getDays() + "天");
6. 格式化和解析
java.time.format.DateTimeFormatter 用于格式化和解析日期时间。
格式化
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = date.format(formatter);
System.out.println("格式化后的日期: " + formattedDate);
解析
String dateString = "2025-02-07";
LocalDate parsedDate = LocalDate.parse(dateString, formatter);
System.out.println("解析后的日期: " + parsedDate);
7. 优点
- 线程安全:
java.time包中的类是不可变的,因此是线程安全的。 - 功能强大:提供了丰富的日期和时间操作方法,支持多种日历系统。
- 易用性:API 设计更加直观和简洁,易于理解和使用。
- 国际化支持:支持多种时区和语言环境。


浙公网安备 33010602011771号