【Java】Java 常用核心类篇 —— 时间-日期API(上)

目录

本地日期类 LocalDate

在 Java 中,LocalDate 是 Java 8 引入的日期处理类,位于 java.time 包下,它用于表示一个不包含时间和时区信息的日期,比如 "2025 - 02 - 21"。以下是关于 LocalDate 的详细介绍:

基本特性

  • 不可变性:LocalDate 是不可变对象,这意味着一旦创建,其状态就不能被修改。每次对 LocalDate 进行操作都会返回一个新的 LocalDate 实例,保证了线程安全。
  • 线程安全:由于其不可变性,LocalDate 可以在多线程环境中安全使用,无需额外的同步机制。
  • 时区无关:LocalDate 只关注日期,不包含时间和时区信息,适用于只需要处理日期的场景。

常用方法

LocalDate 是 Java 8 引入的 java.time 包中的一个重要类,用于表示不包含时间和时区信息的日期。以下将详细介绍 LocalDate 类的所有常用方法。

构造与获取实例相关方法

  • now():获取当前系统默认时区的当前日期。
  • of(int year, int month, int dayOfMonth):根据指定的年、月、日创建一个 LocalDate 实例。这里的月是 1 - 12 之间的整数。
  • ofYearDay(int year, int dayOfYear):根据指定的年份和该年中的第几天创建一个 LocalDate 实例。dayOfYear 的范围是 1 到该年的总天数(平年 365 天,闰年 366 天)。
  • parse(CharSequence text):从符合 ISO - 8601 格式(yyyy-MM-dd)的字符串中解析出 LocalDate 实例。
  • parse(CharSequence text, DateTimeFormatter formatter):使用指定的 DateTimeFormatter 从字符串中解析出 LocalDate 实例,可处理非 ISO - 8601 格式的日期字符串。

以下是代码示例:

java 复制代码
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateExample {
    public static void main(String[] args) {
        // now() 方法示例
        LocalDate currentDate = LocalDate.now();
        System.out.println("now() 方法示例: " + currentDate);

        // of() 方法示例
        LocalDate specificDate = LocalDate.of(2024, 10, 15);
        System.out.println("of() 方法示例: " + specificDate);

        // ofYearDay() 方法示例
        LocalDate yearDayDate = LocalDate.ofYearDay(2024, 100);
        System.out.println("ofYearDay() 方法示例: " + yearDayDate);

        // parse(CharSequence text) 方法示例
        String dateString = "2024-12-25";
        LocalDate parsedDate = LocalDate.parse(dateString);
        System.out.println("parse(CharSequence text) 方法示例: " + parsedDate);

        // parse(CharSequence text, DateTimeFormatter formatter) 方法示例
        String customDateString = "25/12/2024";
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate customParsedDate = LocalDate.parse(customDateString, customFormatter);
        System.out.println("parse(CharSequence text, DateTimeFormatter formatter) 方法示例: " + customParsedDate);
    }
}

获取日期信息相关方法

  • getYear():获取该日期的年份。
  • getMonth():获取该日期的月份,返回 Month 枚举类型。
  • getMonthValue():获取该日期的月份,返回 1 - 12 之间的整数。
  • getDayOfMonth():获取该日期在月份中的天数,范围是 1 - 31。
  • getDayOfYear():获取该日期在年份中的天数,范围是 1 - 366(闰年)。
  • getDayOfWeek():获取该日期是星期几,返回 DayOfWeek 枚举类型。

以下是代码示例:

java 复制代码
import java.time.LocalDate;
import java.time.Month;
import java.time.DayOfWeek;

public class LocalDateInfoExample {
    public static void main(String[] args) {
        // 创建一个 LocalDate 实例
        LocalDate date = LocalDate.of(2025, 5, 15);

        // getYear() 方法示例
        int year = date.getYear();
        System.out.println("getYear() 方法示例: " + year);

        // getMonth() 方法示例
        Month month = date.getMonth();
        System.out.println("getMonth() 方法示例: " + month);

        // getMonthValue() 方法示例
        int monthValue = date.getMonthValue();
        System.out.println("getMonthValue() 方法示例: " + monthValue);

        // getDayOfMonth() 方法示例
        int dayOfMonth = date.getDayOfMonth();
        System.out.println("getDayOfMonth() 方法示例: " + dayOfMonth);

        // getDayOfYear() 方法示例
        int dayOfYear = date.getDayOfYear();
        System.out.println("getDayOfYear() 方法示例: " + dayOfYear);

        // getDayOfWeek() 方法示例
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        System.out.println("getDayOfWeek() 方法示例: " + dayOfWeek);
    }
}

日期计算相关方法

  • plusDays(long daysToAdd):在当前日期的基础上增加指定的天数,返回一个新的 LocalDate 实例。
  • plusWeeks(long weeksToAdd):在当前日期的基础上增加指定的周数,返回一个新的 LocalDate 实例。
  • plusMonths(long monthsToAdd):在当前日期的基础上增加指定的月数,返回一个新的 LocalDate 实例。如果增加后的日期在新月份中不存在,会自动调整到该月的最后一天。
  • plusYears(long yearsToAdd):在当前日期的基础上增加指定的年数,返回一个新的 LocalDate 实例。
  • minusDays(long daysToSubtract):在当前日期的基础上减去指定的天数,返回一个新的 LocalDate 实例。
  • minusWeeks(long weeksToSubtract):在当前日期的基础上减去指定的周数,返回一个新的 LocalDate 实例。
  • minusMonths(long monthsToSubtract):在当前日期的基础上减去指定的月数,返回一个新的 LocalDate 实例。如果减去后的日期在新月份中不存在,会自动调整到该月的最后一天。
  • minusYears(long yearsToSubtract):在当前日期的基础上减去指定的年数,返回一个新的 LocalDate 实例。

以下是代码示例:

java 复制代码
import java.time.LocalDate;

public class LocalDateCalculationExample {
    public static void main(String[] args) {
        // 创建一个 LocalDate 实例
        LocalDate baseDate = LocalDate.of(2025, 2, 21);

        // plusDays 方法示例
        LocalDate dateAfterAddingDays = baseDate.plusDays(5);
        System.out.println("plusDays 方法示例: " + dateAfterAddingDays);

        // plusWeeks 方法示例
        LocalDate dateAfterAddingWeeks = baseDate.plusWeeks(2);
        System.out.println("plusWeeks 方法示例: " + dateAfterAddingWeeks);

        // plusMonths 方法示例
        LocalDate dateAfterAddingMonths = baseDate.plusMonths(3);
        System.out.println("plusMonths 方法示例: " + dateAfterAddingMonths);

        // plusYears 方法示例
        LocalDate dateAfterAddingYears = baseDate.plusYears(1);
        System.out.println("plusYears 方法示例: " + dateAfterAddingYears);

        // minusDays 方法示例
        LocalDate dateAfterMinusDays = baseDate.minusDays(3);
        System.out.println("minusDays 方法示例: " + dateAfterMinusDays);

        // minusWeeks 方法示例
        LocalDate dateAfterMinusWeeks = baseDate.minusWeeks(1);
        System.out.println("minusWeeks 方法示例: " + dateAfterMinusWeeks);

        // minusMonths 方法示例
        LocalDate dateAfterMinusMonths = baseDate.minusMonths(2);
        System.out.println("minusMonths 方法示例: " + dateAfterMinusMonths);

        // minusYears 方法示例
        LocalDate dateAfterMinusYears = baseDate.minusYears(1);
        System.out.println("minusYears 方法示例: " + dateAfterMinusYears);
    }
}

日期比较相关方法

  • isBefore(ChronoLocalDate other):判断当前日期是否在指定日期之前。
  • isAfter(ChronoLocalDate other):判断当前日期是否在指定日期之后。
  • isEqual(ChronoLocalDate other):判断当前日期是否与指定日期相等。

以下是代码示例:

java 复制代码
import java.time.LocalDate;
import java.time.temporal.ChronoLocalDate;

public class LocalDateComparisonExample {
    public static void main(String[] args) {
        // 创建两个 LocalDate 实例
        LocalDate date1 = LocalDate.of(2025, 3, 10);
        LocalDate date2 = LocalDate.of(2025, 4, 15);

        // isBefore 方法示例
        boolean isBeforeResult = date1.isBefore((ChronoLocalDate) date2);
        System.out.println("isBefore 方法示例: " + isBeforeResult);

        // isAfter 方法示例
        boolean isAfterResult = date1.isAfter((ChronoLocalDate) date2);
        System.out.println("isAfter 方法示例: " + isAfterResult);

        // isEqual 方法示例
        LocalDate date3 = LocalDate.of(2025, 3, 10);
        boolean isEqualResult = date1.isEqual((ChronoLocalDate) date3);
        System.out.println("isEqual 方法示例: " + isEqualResult);
    }
}

其他方法

  • isLeapYear():判断该日期所在的年份是否为闰年。
  • lengthOfMonth():获取该日期所在月份的天数。
  • lengthOfYear():获取该日期所在年份的天数,平年 365 天,闰年 366 天。
  • with(TemporalAdjuster adjuster):使用指定的 TemporalAdjuster 调整日期,返回一个新的 LocalDate 实例。例如,可以使用 TemporalAdjusters 类中的静态方法来进行一些常见的调整。
  • format(DateTimeFormatter formatter):使用指定的 DateTimeFormatter 将日期格式化为字符串。

以下是代码示例:

java 复制代码
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class LocalDateOtherMethodsExample {
    public static void main(String[] args) {
        // 创建一个 LocalDate 实例
        LocalDate date = LocalDate.of(2024, 2, 15);

        // isLeapYear 方法示例
        boolean isLeapYear = date.isLeapYear();
        System.out.println("isLeapYear 方法示例: " + isLeapYear);

        // lengthOfMonth 方法示例
        int lengthOfMonth = date.lengthOfMonth();
        System.out.println("lengthOfMonth 方法示例: " + lengthOfMonth);

        // lengthOfYear 方法示例
        int lengthOfYear = date.lengthOfYear();
        System.out.println("lengthOfYear 方法示例: " + lengthOfYear);

        // with 方法示例,调整到当月的最后一天
        LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("with 方法示例: " + lastDayOfMonth);

        // format 方法示例
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String formattedDate = date.format(formatter);
        System.out.println("format 方法示例: " + formattedDate);
    }
}

本地时间类 LocalTime

LocalTime 是 Java 8 引入的 java.time 包中的一个类,用于表示不包含日期和时区信息的时间,例如 13:45:30。它具有不可变性和线程安全性,下面详细介绍 LocalTime 类的常用方法。

基本特性

  • 不可变性:LocalTime 实例一旦创建,其内部状态就不可更改。任何对时间的修改操作都会返回一个新的 LocalTime 实例,这保证了在多线程环境下的线程安全性,多个线程可以同时访问和使用同一个 LocalTime 对象而无需担心数据被意外修改。
  • 时区无关性:LocalTime 仅表示一天中的某个时间点,不包含日期和时区信息。这使得它在只关注时间而不考虑日期和时区的场景下非常实用,例如安排日常的固定时间活动,如会议、课程等。
  • 线程安全:由于其不可变特性,LocalTime 是线程安全的,可在多线程程序中放心使用,无需额外的同步机制。

常用方法

常用构造与获取实例方法

  • now():获取当前系统默认时区的当前时间。
  • of(int hour, int minute):根据指定的小时和分钟创建 LocalTime 实例,秒和纳秒默认为 0。
  • of(int hour, int minute, int second):根据指定的小时、分钟和秒创建 LocalTime 实例,纳秒默认为 0。
  • of(int hour, int minute, int second, int nanoOfSecond):根据指定的小时、分钟、秒和纳秒创建 LocalTime 实例。
  • parse(CharSequence text):从符合 ISO - 8601 格式(HH:mm:ss 或 HH:mm 等)的字符串中解析出 LocalTime 实例。
  • parse(CharSequence text, DateTimeFormatter formatter):使用指定的 DateTimeFormatter 从字符串中解析出 LocalTime 实例,可处理非 ISO - 8601 格式的时间字符串。

以下是代码示例:

java 复制代码
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeExample {
    public static void main(String[] args) {
        // now() 方法示例
        LocalTime currentTime = LocalTime.now();
        System.out.println("now() 方法示例: " + currentTime);

        // of(int hour, int minute) 方法示例
        LocalTime time1 = LocalTime.of(10, 30);
        System.out.println("of(int hour, int minute) 方法示例: " + time1);

        // of(int hour, int minute, int second) 方法示例
        LocalTime time2 = LocalTime.of(14, 45, 20);
        System.out.println("of(int hour, int minute, int second) 方法示例: " + time2);

        // of(int hour, int minute, int second, int nanoOfSecond) 方法示例
        LocalTime time3 = LocalTime.of(16, 15, 30, 500000000);
        System.out.println("of(int hour, int minute, int second, int nanoOfSecond) 方法示例: " + time3);

        // parse(CharSequence text) 方法示例
        String timeStr1 = "18:20";
        LocalTime parsedTime1 = LocalTime.parse(timeStr1);
        System.out.println("parse(CharSequence text) 方法示例: " + parsedTime1);

        // parse(CharSequence text, DateTimeFormatter formatter) 方法示例
        String timeStr2 = "20:35:10";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime parsedTime2 = LocalTime.parse(timeStr2, formatter);
        System.out.println("parse(CharSequence text, DateTimeFormatter formatter) 方法示例: " + parsedTime2);
    }
}

获取时间信息方法

  • getHour():获取时间的小时部分,范围是 0 - 23。
  • getMinute():获取时间的分钟部分,范围是 0 - 59。
  • getSecond():获取时间的秒部分,范围是 0 - 59。
  • getNano():获取时间的纳秒部分,范围是 0 - 999,999,999。

以下是代码示例:

java 复制代码
import java.time.LocalTime;

public class LocalTimeInfoExample {
    public static void main(String[] args) {
        // 创建一个 LocalTime 实例
        LocalTime time = LocalTime.of(15, 35, 20, 500000000);

        // getHour 方法示例
        int hour = time.getHour();
        System.out.println("getHour 方法示例: " + hour);

        // getMinute 方法示例
        int minute = time.getMinute();
        System.out.println("getMinute 方法示例: " + minute);

        // getSecond 方法示例
        int second = time.getSecond();
        System.out.println("getSecond 方法示例: " + second);

        // getNano 方法示例
        int nano = time.getNano();
        System.out.println("getNano 方法示例: " + nano);
    }
}

时间计算方法

  • plusHours(long hoursToAdd):在当前时间的基础上增加指定的小时数,返回一个新的 LocalTime 实例。
  • plusMinutes(long minutesToAdd):在当前时间的基础上增加指定的分钟数,返回一个新的 LocalTime 实例。
  • plusSeconds(long secondsToAdd):在当前时间的基础上增加指定的秒数,返回一个新的 LocalTime 实例。
  • plusNanos(long nanosToAdd):在当前时间的基础上增加指定的纳秒数,返回一个新的 LocalTime 实例。
  • minusHours(long hoursToSubtract):在当前时间的基础上减去指定的小时数,返回一个新的 LocalTime 实例。
  • minusMinutes(long minutesToSubtract):在当前时间的基础上减去指定的分钟数,返回一个新的 LocalTime 实例。
  • minusSeconds(long secondsToSubtract):在当前时间的基础上减去指定的秒数,返回一个新的 LocalTime 实例。
  • minusNanos(long nanosToSubtract):在当前时间的基础上减去指定的纳秒数,返回一个新的 LocalTime 实例。

以下是代码示例:

java 复制代码
import java.time.LocalTime;

public class LocalTimeCalculationExample {
    public static void main(String[] args) {
        // 创建一个 LocalTime 实例
        LocalTime baseTime = LocalTime.of(10, 30, 20, 500000000);

        // plusHours 方法示例
        LocalTime timeAfterAddingHours = baseTime.plusHours(2);
        System.out.println("plusHours 方法示例: " + timeAfterAddingHours);

        // plusMinutes 方法示例
        LocalTime timeAfterAddingMinutes = baseTime.plusMinutes(15);
        System.out.println("plusMinutes 方法示例: " + timeAfterAddingMinutes);

        // plusSeconds 方法示例
        LocalTime timeAfterAddingSeconds = baseTime.plusSeconds(30);
        System.out.println("plusSeconds 方法示例: " + timeAfterAddingSeconds);

        // plusNanos 方法示例
        LocalTime timeAfterAddingNanos = baseTime.plusNanos(500000000);
        System.out.println("plusNanos 方法示例: " + timeAfterAddingNanos);

        // minusHours 方法示例
        LocalTime timeAfterMinusHours = baseTime.minusHours(1);
        System.out.println("minusHours 方法示例: " + timeAfterMinusHours);

        // minusMinutes 方法示例
        LocalTime timeAfterMinusMinutes = baseTime.minusMinutes(10);
        System.out.println("minusMinutes 方法示例: " + timeAfterMinusMinutes);

        // minusSeconds 方法示例
        LocalTime timeAfterMinusSeconds = baseTime.minusSeconds(15);
        System.out.println("minusSeconds 方法示例: " + timeAfterMinusSeconds);

        // minusNanos 方法示例
        LocalTime timeAfterMinusNanos = baseTime.minusNanos(300000000);
        System.out.println("minusNanos 方法示例: " + timeAfterMinusNanos);
    }
}

时间比较方法

  • isBefore(LocalTime other):判断当前时间是否在指定时间之前。
  • isAfter(LocalTime other):判断当前时间是否在指定时间之后。
  • isEqual(LocalTime other):判断当前时间是否与指定时间相等。

以下是代码示例:

java 复制代码
import java.time.LocalTime;

public class LocalTimeComparisonExample {
    public static void main(String[] args) {
        // 创建两个 LocalTime 实例
        LocalTime time1 = LocalTime.of(10, 30, 0);
        LocalTime time2 = LocalTime.of(11, 30, 0);

        // isBefore 方法示例
        boolean isBeforeResult = time1.isBefore(time2);
        System.out.println("isBefore 方法示例: " + isBeforeResult);

        // isAfter 方法示例
        boolean isAfterResult = time1.isAfter(time2);
        System.out.println("isAfter 方法示例: " + isAfterResult);

        // isEqual 方法示例
        LocalTime time3 = LocalTime.of(10, 30, 0);
        boolean isEqualResult = time1.isEqual(time3);
        System.out.println("isEqual 方法示例: " + isEqualResult);
    }
}

其他方法

  • withHour(int hour):返回一个新的 LocalTime 实例,将小时部分设置为指定的值。
  • withMinute(int minute):返回一个新的 LocalTime 实例,将分钟部分设置为指定的值。
  • withSecond(int second):返回一个新的 LocalTime 实例,将秒部分设置为指定的值。
  • withNano(int nanoOfSecond):返回一个新的 LocalTime 实例,将纳秒部分设置为指定的值。
  • format(DateTimeFormatter formatter):使用指定的 DateTimeFormatter 将时间格式化为字符串。

以下是代码示例:

java 复制代码
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeOtherMethodsExample {
    public static void main(String[] args) {
        // 创建一个 LocalTime 实例
        LocalTime time = LocalTime.of(14, 25, 30, 500000000);

        // withHour 方法示例
        LocalTime newTimeWithHour = time.withHour(16);
        System.out.println("withHour 方法示例: " + newTimeWithHour);

        // withMinute 方法示例
        LocalTime newTimeWithMinute = time.withMinute(40);
        System.out.println("withMinute 方法示例: " + newTimeWithMinute);

        // withSecond 方法示例
        LocalTime newTimeWithSecond = time.withSecond(15);
        System.out.println("withSecond 方法示例: " + newTimeWithSecond);

        // withNano 方法示例
        LocalTime newTimeWithNano = time.withNano(200000000);
        System.out.println("withNano 方法示例: " + newTimeWithNano);

        // format 方法示例
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS");
        String formattedTime = time.format(formatter);
        System.out.println("format 方法示例: " + formattedTime);
    }
}
相关推荐
猎人everest37 分钟前
SpringBoot应用开发入门
java·spring boot·后端
山猪打不过家猪3 小时前
ASP.NET Core Clean Architecture
java·数据库·asp.net
AllowM3 小时前
【LeetCode Hot100】除自身以外数组的乘积|左右乘积列表,Java实现!图解+代码,小白也能秒懂!
java·算法·leetcode
Biomamba生信基地3 小时前
两天入门R语言,周末开讲
开发语言·r语言·生信
RAN_PAND3 小时前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法
Bio Coder3 小时前
R语言安装生物信息数据库包
开发语言·数据库·r语言
Tiger Z3 小时前
R 语言科研绘图第 27 期 --- 密度图-分组
开发语言·程序人生·r语言·贴图
不会Hello World的小苗3 小时前
Java——列表(List)
java·python·list
二十七剑4 小时前
jvm中各个参数的理解
java·jvm