java 时间如何计算
时间计算的基本方法
Java中处理时间计算通常使用java.time包(Java 8及以上版本),提供LocalDate、LocalTime、LocalDateTime等类。
获取当前时间

LocalDateTime now = LocalDateTime.now(); // 当前日期和时间
LocalDate today = LocalDate.now(); // 当前日期
LocalTime currentTime = LocalTime.now(); // 当前时间
时间加减操作
使用plus和minus方法,支持年、月、日、小时等单位:
LocalDateTime future = now.plusDays(7); // 加7天
LocalDateTime past = now.minusHours(3); // 减3小时
计算时间差
通过ChronoUnit或Duration/Period类:

long daysBetween = ChronoUnit.DAYS.between(
LocalDate.of(2023, 1, 1),
LocalDate.of(2023, 1, 10) // 结果为9天
);
Duration duration = Duration.between(
LocalTime.of(10, 0),
LocalTime.of(12, 30) // 结果为PT2H30M(2小时30分钟)
);
时区处理
使用ZonedDateTime处理带时区的时间:
ZonedDateTime zonedNow = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime newYorkTime = zonedNow.withZoneSameInstant(ZoneId.of("America/New_York"));
时间格式化与解析
通过DateTimeFormatter实现字符串与时间的转换:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter); // 转为字符串
LocalDateTime parsed = LocalDateTime.parse("2023-01-01 12:00", formatter); // 字符串转时间
注意事项
- 旧版Java(<8)可使用
java.util.Date和Calendar,但推荐迁移到java.time。 - 夏令时和时区转换需谨慎处理,建议明确指定时区。
- 精确计算(如纳秒级)需使用
Instant类。






