好的!下面给你一份关于 Java 中 LocalDateTime 的全面详解与实用案例,内容涵盖基本用法、常见操作、格式化、时区转换等,适合深入学习和实战参考。
Java LocalDateTime 全面详解与实用案例
一、什么是 LocalDateTime?
LocalDateTime
是 Java 8 引入的日期时间API(java.time包)的一部分- 表示没有时区信息的日期时间,包含年月日时分秒纳秒
- 线程安全,替代老的
java.util.Date
和java.util.Calendar
二、LocalDateTime 的创建
import java.time.LocalDateTime;
import java.time.Month;
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 指定年月日时分秒创建
LocalDateTime dateTime = LocalDateTime.of(2025, Month.AUGUST, 13, 9, 30, 0);
// 通过字符串解析(需配合DateTimeFormatter)
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse("2025-08-13 09:30:00", formatter);
三、LocalDateTime 常用方法
方法 | 说明 |
---|---|
getYear() | 获取年份 |
getMonth() | 获取月份(Month枚举) |
getMonthValue() | 获取月份数字(1-12) |
getDayOfMonth() | 获取日 |
getHour() | 获取小时(0-23) |
getMinute() | 获取分钟 |
getSecond() | 获取秒 |
plusDays(long) | 增加天数 |
minusHours(long) | 减少小时 |
withYear(int) | 修改年份 |
isBefore(other) | 判断是否早于另一个LocalDateTime |
isAfter(other) | 判断是否晚于另一个LocalDateTime |
四、格式化与解析
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// LocalDateTime -> String
String formatted = now.format(formatter);
// String -> LocalDateTime
LocalDateTime dt = LocalDateTime.parse("2025-08-13 09:30:00", formatter);
五、时区转换
LocalDateTime
无时区信息,转换时需要配合 ZonedDateTime
或 OffsetDateTime
。
import java.time.ZoneId;
import java.time.ZonedDateTime;
// 转换为某个时区的时间
ZonedDateTime zdt = now.atZone(ZoneId.systemDefault());
ZonedDateTime nyTime = zdt.withZoneSameInstant(ZoneId.of("America/New_York"));
六、实用案例
1. 计算两个时间差
import java.time.Duration;
LocalDateTime start = LocalDateTime.of(2025, 8, 13, 8, 0);
LocalDateTime end = LocalDateTime.of(2025, 8, 13, 10, 30);
Duration duration = Duration.between(start, end);
System.out.println("相差分钟数:" + duration.toMinutes());
2. 判断日期是否在某个范围内
LocalDateTime now = LocalDateTime.now();
LocalDateTime start = LocalDateTime.of(2025, 1, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2025, 12, 31, 23, 59);
boolean inRange = now.isAfter(start) && now.isBefore(end);
System.out.println("是否在范围内:" + inRange);
3. 生成文件名带时间戳
String fileName = "backup_" + now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".zip";
System.out.println(fileName);
七、总结
LocalDateTime
适合无时区场景的日期时间操作- 结合
DateTimeFormatter
实现格式化和解析 - 利用
ZonedDateTime
实现时区转换 - 丰富的API支持时间加减、比较等操作,方便业务开发
好的!下面给你几个更复杂的 LocalDateTime 用例,涵盖跨时区时间计算、定时任务触发时间计算、以及格式转换等实战场景,帮助你深入理解和应用。
Java LocalDateTime 进阶实战案例
1. 跨时区时间计算
假设你有纽约时间的某个事件,需要转换成北京时间,并计算两个时区时间的差异。
import java.time.*;
public class TimezoneExample {
public static void main(String[] args) {
// 纽约时间
ZoneId newYorkZone = ZoneId.of("America/New_York");
LocalDateTime nyLocalTime = LocalDateTime.of(2025, 8, 13, 10, 0);
ZonedDateTime nyZoned = nyLocalTime.atZone(newYorkZone);
System.out.println("纽约时间:" + nyZoned);
// 转换为北京时间(亚洲/上海)
ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
ZonedDateTime shanghaiZoned = nyZoned.withZoneSameInstant(shanghaiZone);
System.out.println("北京时间:" + shanghaiZoned);
// 计算两个时间的差值(毫秒)
Duration duration = Duration.between(nyZoned.toInstant(), shanghaiZoned.toInstant());
System.out.println("时差(小时):" + duration.toHours());
}
}
2. 定时任务下次触发时间计算
假设你有一个每天固定时间(比如每天09:30)的定时任务,现根据当前时间计算下一次触发时间。
import java.time.*;
public class SchedulerExample {
public static void main(String[] args) {
LocalTime targetTime = LocalTime.of(9, 30); // 每天9:30
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextRun = now.withHour(targetTime.getHour())
.withMinute(targetTime.getMinute())
.withSecond(0)
.withNano(0);
// 如果今天的时间已过,触发时间推迟到明天
if (now.compareTo(nextRun) >= 0) {
nextRun = nextRun.plusDays(1);
}
System.out.println("当前时间:" + now);
System.out.println("下一次触发时间:" + nextRun);
}
}
3. 不同格式时间字符串互转
从一种格式时间字符串转换为另一种格式。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatConvertExample {
public static void main(String[] args) {
String source = "13-Aug-2025 09:30:00";
DateTimeFormatter sourceFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss");
DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(source, sourceFormat);
String result = dateTime.format(targetFormat);
System.out.println("转换前:" + source);
System.out.println("转换后:" + result);
}
}
4. 计算两日期之间的天数、月数、年数差
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DateDifferenceExample {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.of(2025, 8, 13);
long days = ChronoUnit.DAYS.between(start, end);
long months = ChronoUnit.MONTHS.between(start, end);
long years = ChronoUnit.YEARS.between(start, end);
System.out.println("相差天数:" + days);
System.out.println("相差月数:" + months);
System.out.println("相差年数:" + years);
}
}
5. 获取当前时间的秒级时间戳和毫秒时间戳
import java.time.Instant;
public class TimestampExample {
public static void main(String[] args) {
Instant now = Instant.now();
long epochSeconds = now.getEpochSecond(); // 秒级时间戳
long epochMilli = now.toEpochMilli(); // 毫秒级时间戳
System.out.println("当前秒级时间戳:" + epochSeconds);
System.out.println("当前毫秒级时间戳:" + epochMilli);
}
}
发表回复