Java LocalDateTime 类

LocalDateTime 是 Java 8 引入的日期时间 API(java.time 包)中的一个重要类,它表示一个不可变的日期时间对象,不包含时区信息。这个类可以存储年、月、日、时、分、秒和纳秒级别的日期时间信息。

LocalDateTime 的特点

  1. 不可变性:所有 java.time 类都是不可变的,线程安全
  2. 不包含时区:只表示本地日期和时间
  3. 精确到纳秒:可以表示精确到纳秒级别的时间
  4. 丰富的 API:提供了大量方法用于日期时间计算和格式化

创建 LocalDateTime 对象

1. 使用静态工厂方法

实例

// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();

// 使用指定的日期和时间创建
LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 14, 30, 45);

// 使用年、月、日、时、分
LocalDateTime dateTime1 = LocalDateTime.of(2023, Month.MAY, 15, 14, 30);

// 使用年、月、日、时、分、秒
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 15, 14, 30, 45);

// 使用年、月、日、时、分、秒、纳秒
LocalDateTime dateTime3 = LocalDateTime.of(2023, 5, 15, 14, 30, 45, 100);

2. 从 LocalDate 和 LocalTime 组合

实例

LocalDate date = LocalDate.of(2023, 5, 15);
LocalTime time = LocalTime.of(14, 30, 45);
LocalDateTime dateTime = LocalDateTime.of(date, time);

3. 解析字符串

实例

LocalDateTime parsedDateTime = LocalDateTime.parse("2023-05-15T14:30:45");

常用操作方法

获取日期时间各部分

实例

LocalDateTime dateTime = LocalDateTime.now();

int year = dateTime.getYear();
Month month = dateTime.getMonth(); // 返回 Month 枚举
int monthValue = dateTime.getMonthValue(); // 返回 1-12
int day = dateTime.getDayOfMonth();
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
int nano = dateTime.getNano();

日期时间计算

实例

LocalDateTime dateTime = LocalDateTime.now();

// 加操作
LocalDateTime plusYears = dateTime.plusYears(1);
LocalDateTime plusMonths = dateTime.plusMonths(1);
LocalDateTime plusDays = dateTime.plusDays(1);
LocalDateTime plusHours = dateTime.plusHours(1);
LocalDateTime plusMinutes = dateTime.plusMinutes(1);
LocalDateTime plusSeconds = dateTime.plusSeconds(1);

// 减操作
LocalDateTime minusYears = dateTime.minusYears(1);
LocalDateTime minusDays = dateTime.minusDays(1);
// 其他减操作类似...

日期时间比较

实例

LocalDateTime dateTime1 = LocalDateTime.of(2023, 5, 15, 14, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 16, 14, 30);

boolean isBefore = dateTime1.isBefore(dateTime2); // true
boolean isAfter = dateTime1.isAfter(dateTime2); // false
boolean isEqual = dateTime1.isEqual(dateTime2); // false

调整日期时间

实例

LocalDateTime dateTime = LocalDateTime.now();

// 修改特定字段
LocalDateTime withYear = dateTime.withYear(2024);
LocalDateTime withHour = dateTime.withHour(15);
// 其他字段类似...

// 使用 TemporalAdjusters
LocalDateTime firstDayOfMonth = dateTime.with(TemporalAdjusters.firstDayOfMonth());
LocalDateTime lastDayOfYear = dateTime.with(TemporalAdjusters.lastDayOfYear());

格式化与解析

格式化日期时间

实例

LocalDateTime dateTime = LocalDateTime.now();

// 使用预定义的格式
DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
String formatted = dateTime.format(isoDateTime);

// 自定义格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String customFormatted = dateTime.format(formatter);

解析字符串为日期时间

实例

String str = "2023-05-15 14:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse(str, formatter);

与其他日期时间类的转换

转换为 LocalDate 和 LocalTime

实例

LocalDateTime dateTime = LocalDateTime.now();

LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();

与 Instant 和 ZonedDateTime 的转换

实例

// 需要时区信息
ZoneId zone = ZoneId.systemDefault();

// LocalDateTime 转 ZonedDateTime
ZonedDateTime zonedDateTime = dateTime.atZone(zone);

// ZonedDateTime 转 LocalDateTime
LocalDateTime fromZoned = zonedDateTime.toLocalDateTime();

// LocalDateTime 转 Instant
Instant instant = zonedDateTime.toInstant();

// Instant 转 LocalDateTime
LocalDateTime fromInstant = LocalDateTime.ofInstant(instant, zone);

实际应用示例

计算两个日期时间之间的间隔

实例

LocalDateTime start = LocalDateTime.of(2023, 5, 15, 9, 0);
LocalDateTime end = LocalDateTime.of(2023, 5, 16, 17, 30);

Duration duration = Duration.between(start, end);

long hours = duration.toHours(); // 32
long minutes = duration.toMinutes(); // 1950

检查日期是否在特定范围内

实例

LocalDateTime checkDate = LocalDateTime.of(2023, 5, 15, 14, 0);
LocalDateTime startDate = LocalDateTime.of(2023, 5, 1, 0, 0);
LocalDateTime endDate = LocalDateTime.of(2023, 5, 31, 23, 59);

boolean isInRange = !checkDate.isBefore(startDate) && !checkDate.isAfter(endDate);

生成日期时间序列

实例

LocalDateTime start = LocalDateTime.of(2023, 5, 1, 9, 0);
List<LocalDateTime> dateTimes = new ArrayList<>();

for (int i = 0; i < 10; i++) {
    dateTimes.add(start.plusDays(i));
}

总结

LocalDateTime 类是 Java 8 日期时间 API 中非常实用的一个类,它提供了丰富的方法来处理不含时区的日期和时间。通过本文的学习,你应该已经掌握了:

  1. 如何创建 LocalDateTime 对象
  2. 如何进行日期时间的计算和比较
  3. 如何格式化和解析日期时间
  4. 如何与其他日期时间类进行转换
  5. 一些实际应用场景

LocalDateTime 非常适合处理不需要时区信息的业务场景,如生日、会议时间等。对于需要时区处理的场景,应该考虑使用 ZonedDateTime 类。

静态工厂方法

方法 描述 示例
static LocalDateTime now() 获取当前日期时间 LocalDateTime.now()
static LocalDateTime of(int year, int month, int day, int hour, int minute) 指定年月日时分创建 LocalDateTime.of(2023, 6, 15, 14, 30)
static LocalDateTime of(int year, int month, int day, int hour, int minute, int second) 指定年月日时分秒创建 LocalDateTime.of(2023, 6, 15, 14, 30, 45)
static LocalDateTime of(int year, Month month, int day, int hour, int minute) 使用Month枚举创建 LocalDateTime.of(2023, Month.JUNE, 15, 14, 30)
static LocalDateTime of(LocalDate date, LocalTime time) 组合LocalDate和LocalTime创建 LocalDateTime.of(LocalDate.now(), LocalTime.now())
static LocalDateTime parse(CharSequence text) 从字符串解析(ISO格式) LocalDateTime.parse("2023-06-15T14:30:45")
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) 使用指定格式解析 LocalDateTime.parse("15/06/2023 14:30", DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"))

获取日期时间信息

方法 描述 示例
int getYear() 获取年份 2023
Month getMonth() 获取月份(Month枚举) Month.JUNE
int getMonthValue() 获取月份值(1-12) 6
int getDayOfMonth() 获取月中的天数 15
int getDayOfYear() 获取年中的天数 166
DayOfWeek getDayOfWeek() 获取星期几(DayOfWeek枚举) DayOfWeek.THURSDAY
int getHour() 获取小时(0-23) 14
int getMinute() 获取分钟(0-59) 30
int getSecond() 获取秒数(0-59) 45
int getNano() 获取纳秒数 0

日期时间操作

方法 描述 示例
LocalDateTime plusDays(long days) 添加天数 dt.plusDays(5)
LocalDateTime plusHours(long hours) 添加小时 dt.plusHours(2)
LocalDateTime plusMinutes(long minutes) 添加分钟 dt.plusMinutes(30)
LocalDateTime plusSeconds(long seconds) 添加秒数 dt.plusSeconds(45)
LocalDateTime plusNanos(long nanos) 添加纳秒 dt.plusNanos(1000000)
LocalDateTime minusDays(long days) 减去天数 dt.minusDays(5)
LocalDateTime minusHours(long hours) 减去小时 dt.minusHours(2)
LocalDateTime minusMinutes(long minutes) 减去分钟 dt.minusMinutes(30)
LocalDateTime minusSeconds(long seconds) 减去秒数 dt.minusSeconds(45)
LocalDateTime minusNanos(long nanos) 减去纳秒 dt.minusNanos(1000000)
LocalDateTime withYear(int year) 修改年份 dt.withYear(2024)
LocalDateTime withMonth(int month) 修改月份 dt.withMonth(12)
LocalDateTime withDayOfMonth(int day) 修改月中的天数 dt.withDayOfMonth(1)
LocalDateTime withHour(int hour) 修改小时 dt.withHour(0)
LocalDateTime withMinute(int minute) 修改分钟 dt.withMinute(0)
LocalDateTime withSecond(int second) 修改秒数 dt.withSecond(0)
LocalDateTime withNano(int nano) 修改纳秒 dt.withNano(0)

日期时间比较

方法 描述 示例
boolean isAfter(ChronoLocalDateTime<?> other) 是否在指定日期时间之后 dt1.isAfter(dt2)
boolean isBefore(ChronoLocalDateTime<?> other) 是否在指定日期时间之前 dt1.isBefore(dt2)
boolean isEqual(ChronoLocalDateTime<?> other) 是否等于指定日期时间 dt1.isEqual(dt2)
int compareTo(ChronoLocalDateTime<?> other) 比较两个日期时间 dt1.compareTo(dt2)

转换方法

方法 描述 示例
LocalDate toLocalDate() 转换为LocalDate dt.toLocalDate()
LocalTime toLocalTime() 转换为LocalTime dt.toLocalTime()
Instant toInstant(ZoneOffset offset) 转换为Instant dt.toInstant(ZoneOffset.UTC)
ZonedDateTime atZone(ZoneId zone) 转换为ZonedDateTime dt.atZone(ZoneId.of("Asia/Shanghai"))
OffsetDateTime atOffset(ZoneOffset offset) 转换为OffsetDateTime dt.atOffset(ZoneOffset.ofHours(8))

格式化与字符串转换

方法 描述 示例
String format(DateTimeFormatter formatter) 格式化为字符串 dt.format(DateTimeFormatter.ISO_DATE_TIME)
String toString() 转换为ISO格式字符串 "2023-06-15T14:30:45"