Bootstrap

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

本地日期时间类 LocalDateTime

LocalDateTime 是 Java 8 引入的 java.time 包中的一个类,它结合了 LocalDate 和 LocalTime 的功能,用于表示一个不带时区信息的日期和时间,例如 2024 - 10 - 20T14:30:00。以下是关于 LocalDateTime 的详细介绍:

基本特性

  • 不可变性:和 LocalDate、LocalTime 一样,LocalDateTime 是不可变类。一旦创建了一个 LocalDateTime 实例,其内部状态(即表示的日期和时间)不能被修改。任何对 LocalDateTime 进行修改的操作都会返回一个新的 LocalDateTime 实例,这保证了线程安全,在多线程环境下可以放心使用。
  • 时区无关性:LocalDateTime 不包含时区信息,它仅仅表示一个纯粹的日期和时间组合。这在一些只关注本地日期时间,不涉及跨时区问题的场景中非常实用,例如记录日常事件的发生时间。
  • 丰富的 API:提供了丰富的方法用于日期时间的创建、操作、查询和格式化,方便开发者进行各种日期时间处理。

常用方法

构造与获取实例相关方法

  • now():获取当前系统默认时区的当前日期和时间。
  • of(int year, int month, int dayOfMonth, int hour, int minute):根据指定的年、月、日、小时和分钟创建 LocalDateTime 实例,秒和纳秒默认为 0。
  • of(int year, int month, int dayOfMonth, int hour, int minute, int second):根据指定的年、月、日、小时、分钟和秒创建 LocalDateTime 实例,纳秒默认为 0。
  • of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond):根据指定的年、月、日、小时、分钟、秒和纳秒创建 LocalDateTime 实例。
  • of(LocalDate date, LocalTime time):将 LocalDate 和 LocalTime 组合成一个 LocalDateTime 实例。
  • parse(CharSequence text):从符合 ISO - 8601 格式(如 yyyy - MM - ddTHH:mm:ss)的字符串中解析出 LocalDateTime 实例。
  • parse(CharSequence text, DateTimeFormatter formatter):使用指定的 DateTimeFormatter 从字符串中解析出 LocalDateTime 实例,可处理非 ISO - 8601 格式的日期时间字符串。

以下是代码示例:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

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

        // of(int year, int month, int dayOfMonth, int hour, int minute) 方法示例
        LocalDateTime dateTime1 = LocalDateTime.of(2025, 6, 15, 10, 30);
        System.out.println("of(int year, int month, int dayOfMonth, int hour, int minute) 方法示例: " + dateTime1);

        // of(int year, int month, int dayOfMonth, int hour, int minute, int second) 方法示例
        LocalDateTime dateTime2 = LocalDateTime.of(2025, 6, 15, 10, 30, 20);
        System.out.println("of(int year, int month, int dayOfMonth, int hour, int minute, int second) 方法示例: " + dateTime2);

        // of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) 方法示例
        LocalDateTime dateTime3 = LocalDateTime.of(2025, 6, 15, 10, 30, 20, 500000000);
        System.out.println("of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) 方法示例: " + dateTime3);

        // of(LocalDate date, LocalTime time) 方法示例
        LocalDate localDate = LocalDate.of(2025, 6, 15);
        LocalTime localTime = LocalTime.of(10, 30, 20);
        LocalDateTime dateTime4 = LocalDateTime.of(localDate, localTime);
        System.out.println("of(LocalDate date, LocalTime time) 方法示例: " + dateTime4);

        // parse(CharSequence text) 方法示例
        String dateTimeStr1 = "2025-06-15T10:30:20";
        LocalDateTime parsedDateTime1 = LocalDateTime.parse(dateTimeStr1);
        System.out.println("parse(CharSequence text) 方法示例: " + parsedDateTime1);

        // parse(CharSequence text, DateTimeFormatter formatter) 方法示例
        String dateTimeStr2 = "15/06/2025 10:30:20";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        LocalDateTime parsedDateTime2 = LocalDateTime.parse(dateTimeStr2, formatter);
        System.out.println("parse(CharSequence text, DateTimeFormatter formatter) 方法示例: " + parsedDateTime2);
    }
}

获取日期时间信息

  • getYear():获取日期时间中的年份。
  • getMonth():获取日期时间中的月份,返回 Month 枚举类型。
  • getMonthValue():获取日期时间中的月份,返回 1 - 12 之间的整数。
  • getDayOfMonth():获取日期时间中的日(在月份中的天数),范围是 1 - 31。
  • getDayOfYear():获取日期时间中的日(在年份中的天数),范围是 1 - 366(闰年)。
  • getDayOfWeek():获取日期时间是星期几,返回 DayOfWeek 枚举类型。
  • getHour():获取日期时间中的小时部分,范围是 0 - 23。
  • getMinute():获取日期时间中的分钟部分,范围是 0 - 59。
  • getSecond():获取日期时间中的秒部分,范围是 0 - 59。
  • getNano():获取日期时间中的纳秒部分,范围是 0 - 999,999,999。

以下是代码示例:

import java.time.LocalDateTime;
import java.time.Month;
import java.time.DayOfWeek;

public class LocalDateTimeInfoExample {
    public static void main(String[] args) {
        // 创建一个 LocalDateTime 实例
        LocalDateTime dateTime = LocalDateTime.of(2025, 8, 18, 14, 35, 20, 500000000);

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

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

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

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

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

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

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

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

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

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

日期时间计算

  • plusYears(long yearsToAdd):在当前日期时间的基础上增加指定的年数,返回一个新的 LocalDateTime 实例。
  • plusMonths(long monthsToAdd):在当前日期时间的基础上增加指定的月数,返回一个新的 LocalDateTime 实例。如果增加后的日期在新月份中不存在,会自动调整到该月的最后一天。
  • plusWeeks(long weeksToAdd):在当前日期时间的基础上增加指定的周数,返回一个新的 LocalDateTime 实例。
  • plusDays(long daysToAdd):在当前日期时间的基础上增加指定的天数,返回一个新的 LocalDateTime 实例。
  • plusHours(long hoursToAdd):在当前日期时间的基础上增加指定的小时数,返回一个新的 LocalDateTime 实例。
  • plusMinutes(long minutesToAdd):在当前日期时间的基础上增加指定的分钟数,返回一个新的 LocalDateTime 实例。
  • plusSeconds(long secondsToAdd):在当前日期时间的基础上增加指定的秒数,返回一个新的 LocalDateTime 实例。
  • plusNanos(long nanosToAdd):在当前日期时间的基础上增加指定的纳秒数,返回一个新的 LocalDateTime 实例。
  • minusYears(long yearsToSubtract):在当前日期时间的基础上减去指定的年数,返回一个新的 LocalDateTime 实例。
  • minusMonths(long monthsToSubtract):在当前日期时间的基础上减去指定的月数,返回一个新的 LocalDateTime 实例。若减去后的日期在新月份中不存在,会自动调整到该月的最后一天。
  • minusWeeks(long weeksToSubtract):在当前日期时间的基础上减去指定的周数,返回一个新的 LocalDateTime 实例。
  • minusDays(long daysToSubtract):在当前日期时间的基础上减去指定的天数,返回一个新的 LocalDateTime 实例。
  • minusHours(long hoursToSubtract):在当前日期时间的基础上减去指定的小时数,返回一个新的 LocalDateTime 实例。
  • minusMinutes(long minutesToSubtract):在当前日期时间的基础上减去指定的分钟数,返回一个新的 LocalDateTime 实例。
  • minusSeconds(long secondsToSubtract):在当前日期时间的基础上减去指定的秒数,返回一个新的 LocalDateTime 实例。
  • minusNanos(long nanosToSubtract):在当前日期时间的基础上减去指定的纳秒数,返回一个新的 LocalDateTime 实例。

以下是代码示例:

import java.time.LocalDateTime;

public class LocalDateTimeFullCalculationExample {
    public static void main(String[] args) {
        // 创建一个 LocalDateTime 实例
        LocalDateTime baseDateTime = LocalDateTime.of(2025, 5, 31, 12, 30, 20, 500000000);

        // plusYears 方法示例
        LocalDateTime plusYearsResult = baseDateTime.plusYears(1);
        System.out.println("plusYears 方法示例: " + plusYearsResult);

        // plusMonths 方法示例
        LocalDateTime plusMonthsResult = baseDateTime.plusMonths(2);
        System.out.println("plusMonths 方法示例: " + plusMonthsResult);

        // plusWeeks 方法示例
        LocalDateTime plusWeeksResult = baseDateTime.plusWeeks(3);
        System.out.println("plusWeeks 方法示例: " + plusWeeksResult);

        // plusDays 方法示例
        LocalDateTime plusDaysResult = baseDateTime.plusDays(5);
        System.out.println("plusDays 方法示例: " + plusDaysResult);

        // plusHours 方法示例
        LocalDateTime plusHoursResult = baseDateTime.plusHours(2);
        System.out.println("plusHours 方法示例: " + plusHoursResult);

        // plusMinutes 方法示例
        LocalDateTime plusMinutesResult = baseDateTime.plusMinutes(10);
        System.out.println("plusMinutes 方法示例: " + plusMinutesResult);

        // plusSeconds 方法示例
        LocalDateTime plusSecondsResult = baseDateTime.plusSeconds(15);
        System.out.println("plusSeconds 方法示例: " + plusSecondsResult);

        // plusNanos 方法示例
        LocalDateTime plusNanosResult = baseDateTime.plusNanos(500000000);
        System.out.println("plusNanos 方法示例: " + plusNanosResult);

        // minusYears 方法示例
        LocalDateTime minusYearsResult = baseDateTime.minusYears(1);
        System.out.println("minusYears 方法示例: " + minusYearsResult);

        // minusMonths 方法示例
        LocalDateTime minusMonthsResult = baseDateTime.minusMonths(2);
        System.out.println("minusMonths 方法示例: " + minusMonthsResult);

        // minusWeeks 方法示例
        LocalDateTime minusWeeksResult = baseDateTime.minusWeeks(3);
        System.out.println("minusWeeks 方法示例: " + minusWeeksResult);

        // minusDays 方法示例
        LocalDateTime minusDaysResult = baseDateTime.minusDays(5);
        System.out.println("minusDays 方法示例: " + minusDaysResult);

        // minusHours 方法示例
        LocalDateTime minusHoursResult = baseDateTime.minusHours(2);
        System.out.println("minusHours 方法示例: " + minusHoursResult);

        // minusMinutes 方法示例
        LocalDateTime minusMinutesResult = baseDateTime.minusMinutes(10);
        System.out.println("minusMinutes 方法示例: " + minusMinutesResult);

        // minusSeconds 方法示例
        LocalDateTime minusSecondsResult = baseDateTime.minusSeconds(15);
        System.out.println("minusSeconds 方法示例: " + minusSecondsResult);

        // minusNanos 方法示例
        LocalDateTime minusNanosResult = baseDateTime.minusNanos(500000000);
        System.out.println("minusNanos 方法示例: " + minusNanosResult);
    }
}

日期时间比较

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

以下是代码示例:

import java.time.LocalDateTime;

public class LocalDateTimeComparisonExample {
    public static void main(String[] args) {
        // 创建两个 LocalDateTime 实例
        LocalDateTime dateTime1 = LocalDateTime.of(2025, 8, 10, 14, 30, 0);
        LocalDateTime dateTime2 = LocalDateTime.of(2025, 8, 15, 16, 45, 0);

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

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

        // isEqual 方法示例
        LocalDateTime dateTime3 = LocalDateTime.of(2025, 8, 10, 14, 30, 0);
        boolean isEqualResult = dateTime1.isEqual(dateTime3);
        System.out.println("isEqual 方法示例: " + isEqualResult);
    }
}

其他方法

  • toLocalDate():从 LocalDateTime 中提取 LocalDate 部分。
  • toLocalTime():从 LocalDateTime 中提取 LocalTime 部分。
  • format(DateTimeFormatter formatter):使用指定的 DateTimeFormatter 将 LocalDateTime 格式化为字符串。
  • with(TemporalAdjuster adjuster):使用指定的 TemporalAdjuster 调整日期时间,返回一个新的 LocalDateTime 实例。例如,可使用 TemporalAdjusters 类中的静态方法进行常见调整。

以下是代码示例:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTimeOtherMethodsExample {
    public static void main(String[] args) {
        // 创建一个 LocalDateTime 实例
        LocalDateTime dateTime = LocalDateTime.of(2025, 10, 20, 15, 45, 30);

        // toLocalDate 方法示例
        LocalDate localDate = dateTime.toLocalDate();
        System.out.println("toLocalDate 方法示例: " + localDate);

        // toLocalTime 方法示例
        LocalTime localTime = dateTime.toLocalTime();
        System.out.println("toLocalTime 方法示例: " + localTime);

        // format 方法示例
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String formattedDateTime = dateTime.format(formatter);
        System.out.println("format 方法示例: " + formattedDateTime);

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

Instant 类、Duration 类和 Period 类

在 Java 中,Instant 类、Duration 类和 Period 类都属于 Java 8 引入的日期和时间 API(java.time 包),它们为处理日期和时间提供了强大而灵活的功能。下面分别对这三个类进行详细介绍。

Instant 类

Instant 类表示时间线上的一个瞬时点,它以 Unix 时间戳(从 1970 年 1 月 1 日 00:00:00 UTC 开始的秒数)为基础,精确到纳秒级别。

常用方法

  • now():获取当前的瞬时点。
  • ofEpochSecond(long epochSecond):根据从 1970-01-01T00:00:00Z 开始的秒数创建 Instant 对象。
  • plus(Duration duration):在当前 Instant 上加上指定的 Duration。
  • isBefore(Instant other)isAfter(Instant other):比较两个 Instant 的先后顺序。

以下是代码示例:

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        // 获取当前的瞬时点
        Instant now = Instant.now();
        System.out.println("当前瞬时点: " + now);

        // 根据秒数创建 Instant 对象
        Instant specificInstant = Instant.ofEpochSecond(1609459200);
        System.out.println("指定秒数的瞬时点: " + specificInstant);

        // 比较两个 Instant
        boolean isBefore = now.isBefore(specificInstant);
        System.out.println("当前瞬时点是否在指定瞬时点之前: " + isBefore);
    }
}

Duration 类

Duration 类用于表示两个 Instant 之间的时间间隔,它以秒和纳秒为单位,适用于处理基于时间的测量,如两个事件之间的持续时间。

常用方法

  • between(Temporal startInclusive, Temporal endExclusive):计算两个 Temporal 对象之间的 Duration。
  • plus(Duration other) 和 minus(Duration other):在当前 Duration 上加上或减去另一个 Duration。
  • toDays()toHours()toMinutes() 等:将 Duration 转换为不同的时间单位。

以下是代码示例:

import java.time.Duration;
import java.time.Instant;

public class DurationExample {
    public static void main(String[] args) {
        // 创建两个 Instant 对象
        Instant start = Instant.ofEpochSecond(1609459200);
        Instant end = Instant.ofEpochSecond(1609545600);

        // 计算两个 Instant 之间的 Duration
        Duration duration = Duration.between(start, end);
        System.out.println("时间间隔: " + duration);

        // 将 Duration 转换为小时
        long hours = duration.toHours();
        System.out.println("时间间隔(小时): " + hours);

        // 在当前 Duration 上加上另一个 Duration
        Duration additionalDuration = Duration.ofHours(2);
        Duration newDuration = duration.plus(additionalDuration);
        System.out.println("加上额外时间后的间隔: " + newDuration);
    }
}

Period 类

Period 类用于表示两个日期之间的时间间隔,它以年、月、日为单位,适用于处理基于日期的测量,如两个人的年龄差。

常用方法

  • between(LocalDate startDateInclusive, LocalDate endDateExclusive):计算两个 LocalDate 对象之间的 Period。
  • plus(Period other) 和 minus(Period other):在当前 Period 上加上或减去另一个 Period。
  • getYears()getMonths()getDays():获取 Period 中的年、月、日数量。

以下是代码示例:

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

public class PeriodExample {
    public static void main(String[] args) {
        // 创建两个 LocalDate 对象
        LocalDate startDate = LocalDate.of(2020, 1, 1);
        LocalDate endDate = LocalDate.of(2022, 3, 15);

        // 计算两个 LocalDate 之间的 Period
        Period period = Period.between(startDate, endDate);
        System.out.println("日期间隔: " + period);

        // 获取 Period 中的年、月、日数量
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        System.out.printf("年: %d, 月: %d, 日: %d%n", years, months, days);

        // 在当前 Period 上加上另一个 Period
        Period additionalPeriod = Period.of(1, 2, 3);
        Period newPeriod = period.plus(additionalPeriod);
        System.out.println("加上额外日期后的间隔: " + newPeriod);
    }
}

总结

  • Instant 类用于表示时间线上的一个精确瞬间。
  • Duration 类用于处理基于时间的间隔,以秒和纳秒为单位。
  • Period 类用于处理基于日期的间隔,以年、月、日为单位。
;