Java常用API(二)

十一、Java常用API(二)

1、StringBuilder

StringBuilder代表可变字符串对象,相当于是一个容器,它里面装的字符串是可以改变的,就是用来操作字符串的
好处:StringBuilder比String更适合做字符串的修改操作,效率会更高,代码也会更简洁

构造器说明
public StringBuilder()创建一个容量为 16 的空 StringBuilder 对象。
public StringBuilder(int capacity)创建一个指定初始容量的空 StringBuilder 对象。
public StringBuilder(CharSequence seq)创建一个包含指定字符序列的 StringBuilder 对象,初始容量为字符序列长度加 16。
public StringBuilder(String str)创建一个包含指定字符串的 StringBuilder 对象,初始容量为字符串长度加 16。
方法名称说明
public StringBuilder append(String str)将指定字符串追加到当前 StringBuilder 对象的末尾,返回当前对象。
public StringBuilder append(char c)将指定字符追加到当前 StringBuilder 对象的末尾,返回当前对象。
public StringBuilder insert(int offset, String str)在指定位置插入指定字符串,返回当前对象。
public StringBuilder delete(int start, int end)删除从起始位置(包含)到结束位置(不包含)的字符序列,返回当前对象。
public StringBuilder replace(int start, int end, String str)用指定字符串替换从起始位置(包含)到结束位置(不包含)的字符序列,返回当前对象。
public StringBuilder reverse()将当前 StringBuilder 对象中的字符序列反转,返回当前对象。
public int length()返回当前 StringBuilder 对象中字符序列的长度。
public String toString()将当前 StringBuilder 对象转换为字符串。
/**
 * @author Tender
 * @date 2025/3/28 13:44
 */

package com.tender.d1_stringbuilderDemo;

public class StringBuilderDemo1 {
    public static void main(String[] args) {
        // 1、创建StringBuilder对象
        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder("三中");
        System.out.println(sb2);

        // 2、拼接内容
        sb.append("甘肃");
        sb.append("Java");
        sb.append(999);

        sb.append("甘肃").append("Java").append(999);
        System.out.println(sb);

        // 3、翻转内容
        sb.reverse();
        System.out.println(sb);

        // 4、拿长度
        System.out.println(sb.length());
        // 5、把StringBuilder对象转换成String对象
        // StringBuilder是拼接字符串的手段
        // String 才是开发中的目的
        String s = sb.toString();
        System.out.println(s);

    }
}

效率测试

/**
 * @author Tender
 * @date 2025/3/28 13:53
 */

package com.tender.d1_stringbuilderDemo;

public class StringBuilderDemo2 {
    public static void main(String[] args) {
        // StringBuilder拼接字符串的性能测试

        /*String s = "";
        for (int i = 0; i < 1000000; i++) {
            s+="abc";
        }
        System.out.println(s);*/
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 1000000; i++) {
            stringBuilder.append("abc");
        }
        System.out.println(stringBuilder);
    }
}

对于字符串相关的操作,如频繁的拼接、修改等,建议使用StringBuilder,效率更高
注意:如果操作字符串较少,或者不需要操作,以及定义字符串变量,还是建议用String

1.1 StringBuilder与StringBuffer

注意:
StringBuffer的用法与StringBuilder是一模一样的,但是StringBuilder是线程不安全的但是StringBuffer只线程安全的
案例:设计一个方法,用于返回任意整型数组的内容,要求返回的数组内容跟格式如:[11, 12, 33]

2、StringJoiner

JDK8开始才有的,根StringBuilder一样,也是用来操作字符串的,也可以看成是一个容器,创建之后里面的内容是可变的
好处:不仅能提高字符串的操作效率,并且有些场景下使用它操作字符串,代码会更简洁

构造器说明
public StringJoiner(CharSequence delimiter)构造一个 StringJoiner 对象,使用指定的分隔符,初始时没有前缀和后缀。
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)构造一个 StringJoiner 对象,使用指定的分隔符、前缀和后缀。
方法名称说明
public StringJoiner add(CharSequence newElement)将给定的字符序列元素添加到 StringJoiner 中,如果已经有元素存在,则先添加分隔符。
public StringJoiner merge(StringJoiner other)将另一个 StringJoiner 的内容合并到当前的 StringJoiner 中,如果另一个 StringJoiner 有元素,会在其内容前加上分隔符。
public int length()返回该 StringJoiner 最终拼接字符串的长度,如果没有元素,返回前缀和后缀的长度之和。
public String toString()返回使用前缀、分隔符、元素和后缀拼接而成的字符串,如果没有添加元素,根据是否设置了空值字符串返回相应内容。
public StringJoiner setEmptyValue(CharSequence emptyValue)设置当 StringJoiner 没有添加任何元素时调用 toString 方法返回的字符串。
/**
 * @author Tender
 * @date 2025/3/28 14:15
 */

package com.tender.d2_StringJoiner;

import java.util.StringJoiner;

public class StringJoinerDemo1 {
    public static void main(String[] args) {
        int[] arr = {33, 44, 55};
        System.out.println(getArrayData(arr));

    }

    public static String getArrayData(int[] arr) {
        if (arr == null){
            return null;
        }
        StringJoiner sj = new StringJoiner(",","[","]");

        for (int i = 0; i < arr.length; i++) {
            int data = arr[i];
            sj.add(Integer.toString(data));
        }

        return sj.toString();
    }
}

2、Math、System、Runtime

2.1 Math

代表数学类,是一个工具类,里面提供的都是对数据进行操作的一些静态方法

方法名说明
public static int abs(int a)返回 int 类型参数的绝对值。对于其他基本数据类型(如 long、float、double)也有对应的 abs 方法。
public static double ceil(double a)返回大于或等于参数的最小整数,结果以 double 类型表示。例如,Math.ceil(3.2) 返回 4.0。
public static double floor(double a)返回小于或等于参数的最大整数,结果以 double 类型表示。例如,Math.floor(3.8) 返回 3.0。
public static long round(double a)返回最接近参数的 long 型整数。对于小数部分大于等于 0.5 的情况,向上取整;小于 0.5 则向下取整。对于 float 类型参数有对应的 round 方法返回 int 类型结果。
public static double max(double a, double b)返回两个 double 类型参数中的较大值。对于 int、long、float 类型也有对应的 max 方法。
public static double min(double a, double b)返回两个 double 类型参数中的较小值。对于 int、long、float 类型也有对应的 min 方法。
public static double pow(double a, double b)返回第一个参数的第二个参数次幂的值,即 a b a^b ab
public static double sqrt(double a)返回 double 类型参数的正平方根。如果参数为负数,返回 NaN。
public static double random()返回一个大于等于 0.0 且小于 1.0 的随机 double 值。
public static double sin(double a)返回角的三角正弦值,参数为弧度。
public static double cos(double a)返回角的三角余弦值,参数为弧度。
public static double tan(double a)返回角的三角正切值,参数为弧度。
public static double asin(double a)返回一个值的反正弦值,返回值范围在 [ − π 2 , π 2 ] [-\frac{\pi}{2}, \frac{\pi}{2}] [2π,2π] 弧度之间。
public static double acos(double a)返回一个值的反余弦值,返回值范围在 [ 0 , π ] [0, \pi] [0,π] 弧度之间。
public static double atan(double a)返回一个值的反正切值,返回值范围在 [ − π 2 , π 2 ] [-\frac{\pi}{2}, \frac{\pi}{2}] [2π,2π] 弧度之间。
public static double toRadians(double angdeg)将角度值转换为弧度值。
public static double toDegrees(double angrad)将弧度值转换为角度值。

2.2 Runtime

代表程序所在的运行环境
Runtime是一个单例类

方法名说明
public static Runtime getRuntime()返回与当前 Java 应用程序关联的运行时对象。由于 Runtime 类是单例模式,该方法是获取 Runtime 实例的唯一方式。
public Process exec(String command) throws IOException在单独的进程中执行指定的字符串命令。例如,可以使用该方法调用系统命令,返回一个 Process 对象,通过该对象可以控制进程并获取进程的输入、输出和错误流。
public Process exec(String[] cmdarray) throws IOException在单独的进程中执行指定的命令和参数数组。与 exec(String command) 类似,但可以更灵活地指定命令及其参数。
public long freeMemory()返回 Java 虚拟机中的空闲内存量,以字节为单位。该值可用于监控内存使用情况。
public long totalMemory()返回 Java 虚拟机中的总内存量,以字节为单位。它表示当前分配给 Java 虚拟机的内存总量。
public long maxMemory()返回 Java 虚拟机试图使用的最大内存量,以字节为单位。如果没有限制,则返回 Long.MAX_VALUE
public void gc()运行垃圾回收器,建议 Java 虚拟机进行垃圾回收,尝试回收未使用的对象以释放内存。
public void exit(int status)终止当前正在运行的 Java 虚拟机。参数 status 为退出状态码,通常非零状态码表示异常终止。

2.2 System

System代表程序所在的系统,也是一个工具类

方法名说明
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)从指定源数组中复制一个数组,从指定位置开始,到目标数组的指定位置。src 是源数组,srcPos 是源数组起始位置,dest 是目标数组,destPos 是目标数组起始位置,length 是要复制的元素数量。
public static long currentTimeMillis()返回当前时间(以毫秒为单位)。可以用于测量代码执行时间,计算时间差等。(返回的是从1970-1-1 00:00:00 走到此刻的总毫秒值)1s=1000ms
public static void exit(int status)终止当前正在运行的 Java 虚拟机。status 为状态码,非零状态码表示异常终止。
public static void gc()运行垃圾回收器,建议 Java 虚拟机进行垃圾回收,尝试回收未使用的对象以释放内存。
public static String getenv(String name)获取指定环境变量的值。如果环境变量不存在,则返回 null
public static Properties getProperties()获取当前系统的属性集合,包含了系统的各种配置信息,如操作系统名称、Java 版本等。
public static String getProperty(String key)获取指定键的系统属性值。如果键不存在,则返回 null
public static String getProperty(String key, String def)获取指定键的系统属性值,如果键不存在,则返回默认值 def
public static PrintStream setOut(PrintStream out)重新分配“标准”输出流。可以将输出重定向到其他地方,比如文件。
public static PrintStream setErr(PrintStream err)重新分配“标准”错误输出流。
public static InputStream setIn(InputStream in)重新分配“标准”输入流。

2.2 BigDecimal

用于解决浮点型运算时,出现结果失真的问题

构造器说明
public BigDecimal(int val)将 int 类型的值转换为 BigDecimal 对象。
public BigDecimal(long val)将 long 类型的值转换为 BigDecimal 对象。
public BigDecimal(double val)将 double 类型的值转换为 BigDecimal 对象,但可能存在精度问题,因为 double 本身存在精度损失。
public BigDecimal(String val)将字符串表示的数值转换为 BigDecimal 对象,推荐使用该构造器以避免精度问题。
public BigDecimal(BigInteger val)将 BigInteger 对象转换为 BigDecimal 对象。
方法名说明
public BigDecimal add(BigDecimal augend)两个 BigDecimal 对象相加,返回一个新的 BigDecimal 对象表示相加结果。
public BigDecimal subtract(BigDecimal subtrahend)两个 BigDecimal 对象相减,返回一个新的 BigDecimal 对象表示相减结果。
public BigDecimal multiply(BigDecimal multiplicand)两个 BigDecimal 对象相乘,返回一个新的 BigDecimal 对象表示相乘结果。
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)两个 BigDecimal 对象相除,指定结果的小数位数和舍入模式,返回一个新的 BigDecimal 对象表示相除结果。
public BigDecimal remainder(BigDecimal divisor)两个 BigDecimal 对象取余,返回一个新的 BigDecimal 对象表示取余结果。
public int compareTo(BigDecimal val)比较两个 BigDecimal 对象的大小,小于返回 -1,等于返回 0,大于返回 1。
public BigDecimal abs()返回该 BigDecimal 对象的绝对值。
public BigDecimal negate()返回该 BigDecimal 对象的相反数。
public int scale()返回该 BigDecimal 对象的小数位数。
public BigDecimal setScale(int newScale, RoundingMode roundingMode)设置该 BigDecimal 对象的小数位数,指定舍入模式,返回一个新的 BigDecimal 对象。
public double doubleValue()将此 BigDecimal 对象转换为 double 类型的值,可能会丢失精度。
public String toString()将 BigDecimal 对象转换为字符串表示。
/**
 * @author Tender
 * @date 2025/3/28 14:44
 */

package com.tender.d4_bigdecimal;

import javax.xml.transform.Source;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalDemo1 {
    public static void main(String[] args) {
        double a = 0.1;
        double b = 0.2;
        double c = a + b;
        System.out.println(c);

        // 1、把两个数据包装成BigDecimal对象
        BigDecimal bd1 = new BigDecimal(Double.toString(a));
        BigDecimal bd2 = new BigDecimal(Double.toString(b));

        // 与上面做法本质一样
        BigDecimal bd11 = BigDecimal.valueOf(a);
        BigDecimal bd22 = BigDecimal.valueOf(b);

        // 2、调用方法进行运算
        BigDecimal add = bd11.add(bd22);
        double c11 = add.doubleValue();
        System.out.println(c11);

        BigDecimal a1 = BigDecimal.valueOf(0.1);
        BigDecimal b1= BigDecimal.valueOf(0.3);

        // 舍入模式
        BigDecimal k = a1.divide(b1,2, RoundingMode.HALF_UP);
        System.out.println(k);


    }
}

3 ZoneId、ZonedDateTime

方法名说明
public static ZoneId systemDefault()获取系统默认的时区。
public static ZoneId of(String zoneId)根据指定的时区 ID 字符串创建 ZoneId 实例。例如,“Asia/Shanghai” 。
public static Set getAvailableZoneIds()获取所有可用的时区 ID 集合。
public String getId()获取该 ZoneId 的 ID 字符串。
方法名说明
public static ZonedDateTime now()获取当前系统默认时区的日期和时间。
public static ZonedDateTime now(ZoneId zone)获取指定时区的当前日期和时间。
public static ZonedDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)根据指定的年、月、日、时、分、秒、纳秒和时区创建 ZonedDateTime 实例。
public ZonedDateTime withZoneSameInstant(ZoneId zone)转换到指定时区,同时保持时间点不变。
public ZonedDateTime withZoneSameLocal(ZoneId zone)转换到指定时区,同时保持本地时间不变。
public LocalDate toLocalDate()提取 ZonedDateTime 中的日期部分,返回 LocalDate 实例。
public LocalTime toLocalTime()提取 ZonedDateTime 中的时间部分,返回 LocalTime 实例。
public ZonedDateTime plusDays(long daysToAdd)在当前日期和时间上增加指定的天数。
public ZonedDateTime minusHours(long hoursToSubtract)在当前日期和时间上减去指定的小时数。
public int compareTo(ZonedDateTime other)比较两个 ZonedDateTime 的先后顺序,返回值小于 0 表示当前对象在前,等于 0 表示相等,大于 0 表示当前对象在后。
package com.tender.d5_jdk8_time;

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

public class Test4_ZoneId_ZonedDateTime {
    public static void main(String[] args) {
        // 目标:了解时区和带时区的时间。
        // 1、ZoneId(用于获取时区的)的常见方法:
        // public static ZoneId systemDefault(): 获取系统默认的时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId.getId());
        System.out.println(zoneId);

        // public static Set<String> getAvailableZoneIds(): 获取Java支持的全部时区Id
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        System.out.println(zoneIds);

        // public static ZoneId of(String zoneId) : 把某个时区id封装成ZoneId对象。
        // America/New_York
        ZoneId an = ZoneId.of("America/New_York");

        // 2、ZonedDateTime:带时区的时间。
        // public static ZonedDateTime now(ZoneId zone): 获取某个时区的ZonedDateTime对象。
        // public static ZonedDateTime now():获取系统默认时区的ZonedDateTime对象
        // ZonedDateTime 的功能和 LocalDateTime一样了

        ZonedDateTime zdt = ZonedDateTime.now(an);
        System.out.println(zdt);

        // 世界标准时间了: 很多服务器要获取世界时间!
        ZonedDateTime utcNow = ZonedDateTime.now(Clock.systemUTC());
        System.out.println(utcNow);
    }
}

3、 LocalDate、LocalTime、LocalDateTime

LocalDate:

package com.tender.d5_jdk8_time;
import java.time.LocalDate;
import java.util.Calendar;

public class Test1_LocalDate {
    public static void main(String[] args) {
        // 0、获取本地日期对象(不可变对象)
        LocalDate ld = LocalDate.now();
        System.out.println(ld);

        // 1、获取日期对象中的信息
        int year = ld.getYear(); // 年
        int month = ld.getMonthValue(); // 月
        int day = ld.getDayOfMonth(); // 日
        int dayOfYear = ld.getDayOfYear();  // 一年中的第几天
        int dayOfWeek = ld.getDayOfWeek().getValue(); // 星期几
        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
        System.out.println(dayOfYear);
        System.out.println(dayOfWeek);

        // 2、直接修改某个信息: withYear、withMonth、withDayOfMonth、withDayOfYear
        LocalDate ld2 = ld.withYear(2099);
        LocalDate ld3 = ld.withMonth(12);
        System.out.println(ld2);
        System.out.println(ld3);
        System.out.println(ld);

        // 3、把某个信息加多少: plusYears、plusMonths、plusDays、plusWeeks
        LocalDate ld4 = ld.plusYears(2);
        LocalDate ld5 = ld.plusMonths(2);
        System.out.println(ld4);

        // 4、把某个信息减多少:minusYears、minusMonths、minusDays、minusWeeks
        LocalDate ld6 = ld.minusYears(2);
        LocalDate ld7 = ld.minusMonths(2);

        // 5、获取指定日期的LocalDate对象: public static LocalDate of(int year, int month, int dayOfMonth)
        LocalDate ld8 = LocalDate.of(2099, 12, 12);
        LocalDate ld9 = LocalDate.of(2099, 12, 12);

        // 6、判断2个日期对象,是否相等,在前还是在后: equals isBefore isAfter
        System.out.println(ld8.equals(ld9));// true
        System.out.println(ld8.isAfter(ld));  // true
        System.out.println(ld8.isBefore(ld)); // false
    }
}

LocalTime

package com.tender.d5_jdk8_time;
import java.time.LocalTime;

public class Test2_LocalTime {
    public static void main(String[] args) {
        // 0、获取本地时间对象
        LocalTime lt = LocalTime.now(); // 时 分 秒 纳秒 不可变的
        System.out.println(lt);

        // 1、获取时间中的信息
        int hour = lt.getHour(); //时
        int minute = lt.getMinute(); //分
        int second = lt.getSecond(); //秒
        int nano = lt.getNano(); //纳秒

        // 2、修改时间:withHour、withMinute、withSecond、withNano
        LocalTime lt3 = lt.withHour(21);
        LocalTime lt4 = lt.withMinute(10);
        LocalTime lt5 = lt.withSecond(10);
        LocalTime lt6 = lt.withNano(10);
        System.out.println(lt);

        // 3、加多少:plusHours、plusMinutes、plusSeconds、plusNanos
        LocalTime lt7 = lt.plusHours(10);
        LocalTime lt8 = lt.plusMinutes(10);
        LocalTime lt9 = lt.plusSeconds(10);
        LocalTime lt10 = lt.plusNanos(10);

        // 4、减多少:minusHours、minusMinutes、minusSeconds、minusNanos
        LocalTime lt11 = lt.minusHours(10);
        LocalTime lt12 = lt.minusMinutes(10);
        LocalTime lt13 = lt.minusSeconds(10);
        LocalTime lt14 = lt.minusNanos(10);

        // 5、获取指定时间的LocalTime对象:
        // public static LocalTime of(int hour, int minute, int second)
        LocalTime lt15 = LocalTime.of(12, 12, 12);
        LocalTime lt16 = LocalTime.of(12, 12, 12);

        // 6、判断2个时间对象,是否相等,在前还是在后: equals isBefore isAfter
        System.out.println(lt15.equals(lt16)); // true
        System.out.println(lt15.isAfter(lt)); // false
        System.out.println(lt15.isBefore(lt)); // true

    }
}

LocalDateTime

package com.tender.d5_jdk8_time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Test3_LocalDateTime {
    public static void main(String[] args) {
        // 最重要的一个类。
        // 0、获取本地日期和时间对象。
        LocalDateTime ldt = LocalDateTime.now(); // 年 月 日 时 分 秒 纳秒 不可变对象
        System.out.println(ldt);

        // 1、可以获取日期和时间的全部信息
        int year = ldt.getYear(); // 年
        int month = ldt.getMonthValue(); // 月
        int day = ldt.getDayOfMonth(); // 日
        int dayOfYear = ldt.getDayOfYear();  // 一年中的第几天
        int dayOfWeek = ldt.getDayOfWeek().getValue();  // 获取是周几
        int hour = ldt.getHour(); //时
        int minute = ldt.getMinute(); //分
        int second = ldt.getSecond(); //秒
        int nano = ldt.getNano(); //纳秒

        // 2、修改时间信息:
        // withYear withMonth withDayOfMonth withDayOfYear withHour
        // withMinute withSecond withNano
        LocalDateTime ldt2 = ldt.withYear(2029);
        LocalDateTime ldt3 = ldt.withMinute(59);

        // 3、加多少:
        // plusYears  plusMonths plusDays plusWeeks plusHours plusMinutes plusSeconds plusNanos
        LocalDateTime ldt4 = ldt.plusYears(2);
        LocalDateTime ldt5 = ldt.plusMinutes(3);

        // 4、减多少:
        // minusDays minusYears minusMonths minusWeeks minusHours minusMinutes minusSeconds minusNanos
        LocalDateTime ldt6 = ldt.minusYears(2);
        LocalDateTime ldt7 = ldt.minusMinutes(3);


        // 5、获取指定日期和时间的LocalDateTime对象:
        // public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour,
        //                                  int minute, int second, int nanoOfSecond)
        LocalDateTime ldt8 = LocalDateTime.of(2029, 12, 12, 12, 12, 12, 1222);
        LocalDateTime ldt9 = LocalDateTime.of(2029, 12, 12, 12, 12, 12, 1222);

        // 6、 判断2个日期、时间对象,是否相等,在前还是在后: equals、isBefore、isAfter
        System.out.println(ldt9.equals(ldt8));
        System.out.println(ldt9.isAfter(ldt));
        System.out.println(ldt9.isBefore(ldt));

        // 7、可以把LocalDateTime转换成LocalDate和LocalTime
        // public LocalDate toLocalDate()
        // public LocalTime toLocalTime()
        // public static LocalDateTime of(LocalDate date, LocalTime time)
        // 合久必分
        LocalDate ld = ldt.toLocalDate();
        LocalTime lt = ldt.toLocalTime();

        // 分久必合
        LocalDateTime ldt10 = LocalDateTime.of(ld, lt);

    }
}

4、Instant

通过获取instant的对象可以拿到此刻的时间,该时间由两部分组成:从1970-1-1 00:00:00开始走到此刻的总秒数+不够1秒的纳秒数

package com.tender.d5_jdk8_time;

import java.time.Instant;
import java.time.LocalDateTime;

/**
 * 目标:掌握Instant的使用。
 */
public class Test5_Instant {
    public static void main(String[] args) {
       // 1、创建Instant的对象,获取此刻时间信息。
        Instant now = Instant.now();
        System.out.println(now);

        // 2、获取总秒数
        System.out.println(now.getEpochSecond());
        // 3、不够1秒的纳秒数
        System.out.println(now.getNano());

        // Instant对象的作用:做代码的性能分析,或者记录用户的操作时间点
    }
}

5、DateTimeFormatter:格式化器,用于实践的格式化、解析

package com.tender.d5_jdk8_time;

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

/**
 *  目标:掌握JDK 8新增的DateTimeFormatter格式化器的用法。
 */
public class Test6_DateTimeFormatter {
    public static void main(String[] args) {
        // 1、创建一个日期时间格式化器对象出来。
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss EEE a");

        // 2、对时间进行格式化
        LocalDateTime ldt = LocalDateTime.now();

        String result = dtf.format(ldt);
        System.out.println(result);

        // 3、格式化时间,其实还有一种方案。
        String result2 = ldt.format(dtf);
        System.out.println(result2);

        // 4、解析时间:解析时间一般使用LocalDateTime提供的解析方法来解析。
        String dateStr = "2023-11-11 11:11:11";
        // 第一步:必须写一个日期时间格式化器与这个时间的格式一模一样。
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt2 = LocalDateTime.parse(dateStr, dtf2);
        System.out.println(ldt2);
    }
}

5、Period

package com.tender.d5_jdk8_time;

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

/**
 * 目标:掌握Period的作用:计算机两个日期相差的年数,月数、天数。
 */
public class Test7_Period {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2024, 3, 19);
        LocalDate end = LocalDate.of(2024, 10, 13);

        // 1、创建Period对象,封装两个日期对象。
        Period period = Period.between(start, end);

        // 2、通过period对象获取两个日期对象相差的信息。
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
}

6、Duration

可以用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持LocalTime、LocalDateTime、Instant等时间

方法名说明
public static Duration between(Temporal startInclusive, Temporal endExclusive)计算两个时间点之间的时长,startInclusive 是起始时间,endExclusive 是结束时间,返回表示时长的 Duration 对象。这里的 Temporal 可以是 LocalTimeLocalDateTimeZonedDateTime 等实现了 Temporal 接口的类的实例。
public long toDays()获取该 Duration 表示的时长按天计算的值。
public long toHours()获取该 Duration 表示的时长按小时计算的值。
public long toMinutes()获取该 Duration 表示的时长按分钟计算的值。
public long toSeconds()获取该 Duration 表示的时长按秒计算的值。
public long toMillis()获取该 Duration 表示的时长按毫秒计算的值。
public long toNanos()获取该 Duration 表示的时长按纳秒计算的值。
public Duration plus(Duration duration)在当前 Duration 基础上加上另一个 Duration 对象,返回一个新的 Duration 对象表示相加后的时长。
public Duration minus(Duration duration)在当前 Duration 基础上减去另一个 Duration 对象,返回一个新的 Duration 对象表示相减后的时长。
public Duration multipliedBy(long multiplicand)将当前 Duration 乘以指定的倍数,返回一个新的 Duration 对象表示相乘后的时长。
public Duration dividedBy(long divisor)将当前 Duration 除以指定的除数,返回一个新的 Duration 对象表示相除后的时长。
public Duration negated()返回当前 Duration 的相反数,即时长方向相反的 Duration 对象。
public boolean isNegative()判断该 Duration 表示的时长是否为负数。
public boolean isZero()判断该 Duration 表示的时长是否为零。
public int compareTo(Duration otherDuration)比较两个 Duration 对象的大小,小于返回 -1,等于返回 0,大于返回 1。
package com.tender.d5_jdk8_time;

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

public class Test8_Duration {
    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2025, 11, 11, 11, 10, 10);
        LocalDateTime end = LocalDateTime.of(2025, 11, 11, 11, 11, 11);

        // 1、得到Duration对象
        Duration duration = Duration.between(start, end);

        // 2、获取两个时间对象间隔的信息
        System.out.println(duration.toDays());// 间隔多少天
        System.out.println(duration.toHours());// 间隔多少小时
        System.out.println(duration.toMinutes());// 间隔多少分
        System.out.println(duration.toSeconds());// 间隔多少秒
        System.out.println(duration.toMillis());// 间隔多少毫秒
        System.out.println(duration.toNanos());// 间隔多少纳秒
    }
}

案例:高考倒计时

package com.tender.d5_jdk8_time;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test10 {
    public static void main(String[] args) {
        // 目标:高考倒计时。
        // 1、高考时间是
        String startTime = "2025-06-07 09:30:00";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt1 = LocalDateTime.parse(startTime, dtf);

        // 2、知道此刻离高考时间差多少天,多少时,多少分,多少秒。
        LocalDateTime ldt2 = LocalDateTime.now();

        // 3、计算两个时间差
        Duration duration = Duration.between(ldt2, ldt1);
        System.out.println(duration.toDays() + "天" + duration.toHoursPart() + "时"
         + duration.toMinutesPart() + "分" + duration.toSecondsPart() + "秒");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值