Java日期加减实战指南:从基础到高级,解决日期计算常见痛点与陷阱

引言:为什么Java日期处理如此重要且复杂
在现代软件开发中,日期和时间的处理无处不在。无论是用户注册的时间戳、订单的有效期、还是定时任务的调度,都离不开精确的日期计算。然而,Java的日期处理API经历了多次演变,从早期的
java.util.Date
和
java.util.Calendar
,到Java 8引入的全新
java.time
包,这期间积累了许多历史遗留问题和最佳实践。
本文将深入探讨Java日期加减的各个方面,从基础用法到高级技巧,重点解决开发中常见的痛点与陷阱。我们将通过大量实际代码示例,帮助你掌握正确、高效的日期计算方法。
一、Java日期时间API的历史演进
1.1 传统API的缺陷
在Java 8之前,日期时间处理主要依赖
java.util.Date
和
java.util.Calendar
,但这些API存在诸多问题:
可变性
:
Date
和
Calendar
都是可变的,这在多线程环境下容易引发问题
设计混乱
:
Date
中既有日期又有时间,月份从0开始计数(1月=0),容易出错
缺乏时区支持
:原生
Date
不支持时区,需要借助
Calendar
手动处理
API不一致
:方法命名混乱,如
getYear()
返回的是1900年偏移值
1.2 Java 8的革命性改进
Java 8引入了
java.time
包,基于Joda-Time的设计理念,提供了不可变的日期时间类:
核心类
:
LocalDate
、
LocalTime
、
LocalDateTime
、
ZonedDateTime
设计优势
:线程安全、不可变、清晰的API设计、内置时区支持
兼容性
:提供了与旧API的转换方法
二、基础日期加减操作
2.1 使用LocalDate进行日期计算
LocalDate
表示日期(年-月-日),不包含时间信息,适合纯日期计算。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class LocalDateExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate today = LocalDate.now();
System.out.println(“今天: ” + today);

// 基础加减操作
LocalDate tomorrow = today.plusDays(1);
LocalDate nextWeek = today.plusWeeks(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate nextYear = today.plusYears(1);

System.out.println(“明天: ” + tomorrow);
System.out.println(“下周: ” + nextWeek);
System.out.println(“下月: ” + nextMonth);
System.out.println(“明年: ” + nextYear);

// 减法操作
LocalDate yesterday = today.minusDays(1);
LocalDate lastMonth = today.minusMonths(1);
System.out.println(“昨天: ” + yesterday);
System.out.println(“上月: ” + lastMonth);

// 使用ChronoUnit进行精确计算
long daysBetween = ChronoUnit.DAYS.between(today, nextYear);
System.out.println(“距离明年还有 ” + daysBetween + ” 天”);
}
}
2.2 使用LocalDateTime进行日期时间计算
LocalDateTime
包含日期和时间,适合需要精确到时分秒的场景。
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(“当前时间: ” + now);

// 精确到小时的加减
LocalDateTime plusHours = now.plusHours(2).plusMinutes(30);
System.out.println(“2小时30分钟后: ” + plusHours);

// 精确到分钟的减法
LocalDateTime minusMinutes = now.minusMinutes(45);
System.out.println(“45分钟前: ” + minusMinutes);

// 使用with方法设置特定字段
LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
System.out.println(“今天零点: ” + startOfDay);

// 计算两个时间点之间的小时差
long hoursBetween = ChronoUnit.HOURS.between(now, plusHours);
System.out.println(“时间差: ” + hoursBetween + ” 小时”);
}
}
2.3 使用ZonedDateTime处理时区
当需要处理不同时区的日期时间时,
ZonedDateTime
是最佳选择。
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
public static void main(String[] args) {
// 获取纽约时区的当前时间
ZonedDateTime nyTime = ZonedDateTime.now(ZoneId.of(“America/New_York”));
System.out.println(“纽约时间: ” + nyTime);

// 转换到东京时区
ZonedDateTime tokyoTime = nyTime.withZoneSameInstant(ZoneId.of(“Asia/Tokyo”));
System.out.println(“东京时间: ” + tokyoTime);

// 在不同时区进行日期加减
ZonedDateTime futureNyTime = nyTime.plusDays(7);
ZonedDateTime futureTokyoTime = tokyoTime.plusDays(7);

System.out.println(“7天后纽约时间: ” + futureNyTime);
System.out.println(“7天后东京时间: ” + futureTokyoTime);

// 验证两个时间点是否表示同一时刻
System.out.println(“是否同一时刻: ” +
(futureNyTime.toInstant().equals(futureTokyoTime.toInstant())));
}
}
三、高级日期计算技巧
3.1 使用Period进行基于日历的计算
Period
基于日历单位(年、月、日),适合处理生日、账单周期等场景。
import java.time.LocalDate;
import java.time.Period;

public class PeriodExample {
public static void main(String[] args) {
LocalDate birthday = LocalDate.of(1990, 5, 15);
LocalDate today = LocalDate.now();

// 计算年龄
Period age = Period.between(birthday, today);
System.out.printf(“年龄: %d岁%d个月%d天%n”,
age.getYears(), age.getMonths(), age.getDays());

// 使用Period进行日期加减
LocalDate threeMonthsLater = today.plus(Period.ofMonths(3));
System.out.println(“3个月后: ” + threeMonthsLater);

// 计算两个日期之间的完整周期
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
Period period = Period.between(startDate, endDate);
System.out.printf(“周期: %d个月%d天%n”, period.getMonths(), period.getDays());

// 创建自定义周期
Period customPeriod = Period.of(1, 2, 15); // 1年2个月15天
LocalDate customDate = today.plus(customPeriod);
System.out.println(“自定义周期后: ” + customDate);
}
}
3.2 使用Duration进行基于时间的计算
Duration
基于时间单位(天、小时、分钟、秒),适合精确时间计算。
import java.time.Duration;
import java.time.LocalDateTime;

public class DurationExample {
public static void main(String[] args) {
LocalDateTime startTime = LocalDateTime.of(2023, 1, 1, 10, 0, 0);
LocalDateTime endTime = LocalDateTime.of(2023, 1, 3, 14, 30, 15);

// 计算精确时间差
Duration duration = Duration.between(startTime, endTime);
System.out.println(“总天数: ” + duration.toDays());
System.out.println(“总小时数: ” + duration.toHours());
System.out.println(“总分钟数: ” + duration.toMinutes());
System.out.println(“总秒数: ” + duration.getSeconds());

// 使用Duration进行时间加减
LocalDateTime newTime = startTime.plus(duration);
System.out.println(“加上时间差后: ” + newTime);

// 创建自定义时长
Duration twoHours = Duration.ofHours(2);
Duration thirtyMinutes = Duration.ofMinutes(30);
Duration combined = twoHours.plus(thirtyMinutes);

LocalDateTime meetingTime = startTime.plus(combined);
System.out.println(“会议时间: ” + meetingTime);

// 检查时间是否在指定时长内
boolean isWithinTwoDays = duration.compareTo(Duration.ofDays(2)) <= 0; System.out.println("是否在2天内: " + isWithinTwoDays); } } 3.3 处理月末和闰年 日期计算中经常需要处理月末和闰年等特殊情况。 import java.time.LocalDate; import java.time.YearMonth; public class EndOfMonthExample { public static void main(String[] args) { LocalDate date = LocalDate.of(2023, 2, 15); // 获取当月最后一天 YearMonth yearMonth = YearMonth.from(date); LocalDate lastDay = yearMonth.atEndOfMonth(); System.out.println("2023年2月最后一天: " + lastDay); // 计算下个月的最后一天 LocalDate nextMonthLastDay = date.plusMonths(1).withDayOfMonth(1).minusDays(1); System.out.println("下个月最后一天: " + nextMonthLastDay); // 处理闰年 LocalDate leapYearDate = LocalDate.of(2024, 2, 29); // 2024是闰年 System.out.println("闰年日期: " + leapYearDate); // 检查是否是闰年 boolean isLeapYear = leapYearDate.isLeapYear(); System.out.println("2024年是闰年: " + isLeapYear); // 安全地计算下个月的同一天(自动处理月末) LocalDate safeNextMonth = date.plusMonths(1); System.out.println("安全计算下月: " + safeNextMonth); // 如果原日期是31号,下个月可能只有30天 LocalDate thirtyFirst = LocalDate.of(2023, 1, 31); LocalDate nextMonth = thirtyFirst.plusMonths(1); System.out.println("1月31日 + 1个月 = " + nextMonth); // 自动调整为2月28日 } } 3.4 使用TemporalAdjuster进行复杂调整 TemporalAdjuster 提供了强大的日期调整能力,可以处理复杂的业务规则。 import java.time.DayOfWeek; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; public class TemporalAdjusterExample { public static void main(String[] args) { LocalDate today = LocalDate.now(); // 下个星期五 LocalDate nextFriday = today.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)); System.out.println("下个星期五: " + nextFriday); // 当月第一个星期一 LocalDate firstMonday = today.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); System.out.println("当月第一个星期一: " + firstMonday); // 当月最后一个星期五 LocalDate lastFriday = today.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)); System.out.println("当月最后一个星期五: " + lastFriday); // 下个月的第三个星期二 LocalDate thirdTuesday = today.plusMonths(1) .with(TemporalAdjusters.firstInMonth(DayOfWeek.TUESDAY)) .plusWeeks(2); System.out.println("下个月第三个星期二: " + thirdTuesday); // 自定义TemporalAdjuster:下一个工作日(跳过周末) LocalDate nextWorkDay = today.with(temporal -> {
LocalDate date = LocalDate.from(temporal);
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek == DayOfWeek.SATURDAY) {
return date.plusDays(2);
} else if (dayOfWeek == DayOfWeek.SUNDAY) {
return date.plusDays(1);
} else {
return date.plusDays(1);
}
});
System.out.println(“下个工作日: ” + nextWorkDay);
}
}
四、常见痛点与陷阱解决方案
4.1 时区处理陷阱
问题
:忽略时区导致的时间计算错误。
解决方案
:始终明确时区,使用
ZonedDateTime
。
import java.time.*;
import java.util.Date;

public class TimeZonePitfall {
public static void main(String[] args) {
// 错误示例:忽略时区
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(“本地时间: ” + localDateTime);

// 转换为不同时区时可能出错
// 错误做法:直接转换
// ZonedDateTime wrongZdt = localDateTime.atZone(ZoneId.systemDefault());

// 正确做法:明确时区
ZonedDateTime correctZdt = ZonedDateTime.now(ZoneId.of(“Asia/Shanghai”));
System.out.println(“上海时间: ” + correctZdt);

// 与旧API Date的转换
Date legacyDate = Date.from(correctZdt.toInstant());
System.out.println(“Legacy Date: ” + legacyDate);

// 从Date转换回新API
Instant instant = legacyDate.toInstant();
ZonedDateTime fromLegacy = instant.atZone(ZoneId.of(“Asia/Shanghai”));
System.out.println(“从Date转换: ” + fromLegacy);

// 处理UTC时间
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println(“UTC时间: ” + utcTime);

// 时区转换
ZonedDateTime beijingTime = utcTime.withZoneSameInstant(ZoneId.of(“Asia/Shanghai”));
System.out.println(“北京时间: ” + beijingTime);
}
}
4.2 月末日期计算陷阱
问题
:当原日期是月末,加减月份时可能得到错误日期。
解决方案
:使用
YearMonth
或接受自动调整。
import java.time.LocalDate;
import java.time.YearMonth;

public class MonthEndPitfall {
public static void main(String[] args) {
// 陷阱示例
LocalDate date1 = LocalDate.of(2023, 1, 31);
LocalDate nextMonth1 = date1.plusMonths(1);
System.out.println(“1月31日 + 1个月 = ” + nextMonth1); // 2月28日(非29日)

LocalDate date2 = LocalDate.of(2023, 3, 31);
LocalDate nextMonth2 = date2.plusMonths(1);
System.out.println(“3月31日 + 1个月 = ” + nextMonth2); // 4月30日

// 正确处理:使用YearMonth
LocalDate date3 = LocalDate.of(2023, 1, 31);
YearMonth yearMonth = YearMonth.from(date3);
LocalDate nextMonth3 = yearMonth.plusMonths(1).atEndOfMonth();
System.out.println(“使用YearMonth: ” + nextMonth3); // 2月28日

// 闰年处理
LocalDate leapDate = LocalDate.of(2024, 1, 31);
YearMonth leapYearMonth = YearMonth.from(leapDate);
LocalDate nextLeapMonth = leapYearMonth.plusMonths(1).atEndOfMonth();
System.out.println(“闰年处理: ” + nextLeapMonth); // 2月29日

// 安全计算:先转到1号再加减
LocalDate safeDate = LocalDate.of(2023, 1, 31);
LocalDate safeNextMonth = safeDate.withDayOfMonth(1).plusMonths(1);
System.out.println(“安全计算: ” + safeNextMonth); // 2月1日
}
}
4.3 夏令时切换陷阱
问题
:夏令时切换时,一天可能只有23或25小时。
解决方案
:使用
ZonedDateTime
处理,避免使用
LocalDateTime
。
import java.time.*;
import java.util.Arrays;
import java.util.List;

public class DaylightSavingPitfall {
public static void main(String[]夏令时切换时,一天可能只有23或25小时。

**解决方案**:使用`ZonedDateTime`处理,避免使用`LocalDateTime`。

“`java
import java.time.*;
import java.util.Arrays;
import java.util.List;

public class DaylightSavingPitfall {
public static void main(String[] args) {
// 夏令时切换日期(美国)
LocalDate dstStart = LocalDate.of(2023, 3, 12); // 3月第二个周日
LocalDate dstEnd = LocalDate.of(2023, 11, 5); // 11月第一个周日

// 在夏令时开始日,2:00 AM直接跳到3:00 AM
ZonedDateTime beforeDst = ZonedDateTime.of(
LocalDate.of(2023, 3, 12),
LocalTime.of(1, 30),
ZoneId.of(“America/New_York”)
);

ZonedDateTime afterDst = beforeDst.plusHours(1);
System.out.println(“夏令时切换前: ” + beforeDst);
System.out.println(“加1小时后: ” + afterDst);
System.out.println(“实际经过: ” +
Duration.between(beforeDst, afterDst).toHours() + ” 小时”);

// 在夏令时结束日,2:00 AM会重复出现
ZonedDateTime beforeDstEnd = ZonedDateTime.of(
LocalDate.of(2023, 11, 5),
LocalTime.of(1, 30),
ZoneId.of(“America/New_York”)
);

ZonedDateTime afterDstEnd = beforeDstEnd.plusHours(1);
System.out.println(“\n夏令时结束前: ” + beforeDstEnd);
System.out.println(“加1小时后: ” + afterDstEnd);

// 避免使用LocalDateTime处理跨夏令时
// 错误做法
LocalDateTime ldt1 = LocalDateTime.of(2023, 3, 12, 1, 30);
LocalDateTime ldt2 = ldt1.plusHours(1); // 2:30,但这个时间在纽约不存在!
System.out.println(“\n错误做法: ” + ldt2);

// 正确做法
ZonedDateTime zdt1 = ZonedDateTime.of(
LocalDate.of(2023, 3, 12),
LocalTime.of(1, 30),
ZoneId.of(“America/New_York”)
);
ZonedDateTime zdt2 = zdt1.plusHours(1);
System.out.println(“正确做法: ” + zdt2);
}
}
4.4 线程安全问题
问题
:传统Date和Calendar是可变的,多线程环境下不安全。
解决方案
:使用java.time包的不可变类。
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.concurrent.*;

public class ThreadSafetyExample {
public static void main(String[] args) throws InterruptedException {
// 传统Date的线程安全问题
// java.util.Date date = new java.util.Date(); // 可变,不安全

// java.time包的不可变性演示
LocalDate date = LocalDate.now();
LocalDate futureDate = date.plusDays(1); // 返回新对象,原对象不变

System.out.println(“原对象: ” + date);
System.out.println(“新对象: ” + futureDate);
System.out.println(“对象相同: ” + (date == futureDate));

// 多线程测试
ExecutorService executor = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(10);

for (int i = 0; i < 10; i++) { final int threadId = i; executor.submit(() -> {
try {
// 并发访问LocalDate
LocalDate now = LocalDate.now();
LocalDate future = now.plusDays(threadId);
System.out.println(“线程 ” + threadId + “: ” + future);
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
}

latch.await();
executor.shutdown();
System.out.println(“所有线程完成”);
}
}
4.5 性能优化技巧
问题
:频繁创建日期对象影响性能。
解决方案
:重用常量、批量计算、使用适当的API。
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class PerformanceOptimization {
// 1. 重用常量
private static final LocalDate BASE_DATE = LocalDate.of(2023, 1, 1);
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(“yyyy-MM-dd”);

public static void main(String[] args) {
// 2. 批量计算
List dateList = new ArrayList<>();
LocalDate current = BASE_DATE;
for (int i = 0; i < 1000; i++) { dateList.add(current); current = current.plusDays(1); // 重用计算结果 } // 3. 避免不必要的对象创建 // 不好:每次循环都创建新对象 for (int i = 0; i < 100; i++) { LocalDate temp = LocalDate.now().plusDays(i); // 每次都创建新对象 // 使用temp... } // 更好:重用基础对象 LocalDate base = LocalDate.now(); for (int i = 0; i < 100; i++) { LocalDate temp = base.plusDays(i); // 基于同一个base计算 // 使用temp... } // 4. 使用适当的精度 // 如果只需要日期,不要用DateTime LocalDate dateOnly = LocalDate.now(); // 比LocalDateTime更轻量 // 5. 格式化性能 long start = System.nanoTime(); for (int i = 0; i < 10000; i++) { String formatted = LocalDate.now().format(FORMATTER); } long end = System.nanoTime(); System.out.println("格式化耗时: " + (end - start) / 1_000_000 + "ms"); } } 五、实际业务场景应用 5.1 计算工作日(排除周末和节假日) import java.time.LocalDate; import java.time.DayOfWeek; import java.util.HashSet; import java.util.Set; public class WorkingDayCalculator { private static final Set HOLIDAYS = new HashSet<>();

static {
// 添加节假日
HOLIDAYS.add(LocalDate.of(2023, 1, 1)); // 元旦
HOLIDAYS.add(LocalDate.of(2023, 5, 1)); // 劳动节
HOLIDAYS.add(LocalDate.of(2023, 10, 1)); // 国庆节
}

/**
* 计算从startDate开始的n个工作日后的日期
*/
public static LocalDate addWorkingDays(LocalDate startDate, int workingDays) {
LocalDate currentDate = startDate;
int count = 0;

while (count < workingDays) { currentDate = currentDate.plusDays(1); if (isWorkingDay(currentDate)) { count++; } } return currentDate; } /** * 判断是否是工作日 */ public static boolean isWorkingDay(LocalDate date) { DayOfWeek dayOfWeek = date.getDayOfWeek(); // 排除周末 if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) { return false; } // 排除节假日 if (HOLIDAYS.contains(date)) { return false; } return true; } public static void main(String[] args) { LocalDate today = LocalDate.of(2023, 5, 8); // 周一 System.out.println("今天: " + today); LocalDate nextWorkDay = addWorkingDays(today, 5); System.out.println("5个工作日后: " + nextWorkDay); // 验证结果 System.out.println("是否是工作日: " + isWorkingDay(nextWorkDay)); } } 5.2 计算两个日期之间的天数(排除周末) import java.time.LocalDate; import java.time.DayOfWeek; import java.time.temporal.ChronoUnit; public class WorkingDaysBetween { /** * 计算两个日期之间的工作日天数 */ public static long calculateWorkingDays(LocalDate start, LocalDate end) { if (start.isAfter(end)) { return 0; } long totalDays = ChronoUnit.DAYS.between(start, end) + 1; long weekends = 0; LocalDate current = start; for (int i = 0; i < totalDays; i++) { DayOfWeek dayOfWeek = current.getDayOfWeek(); if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) { weekends++; } current = current.plusDays(1); } return totalDays - weekends; } public static void main(String[] args) { LocalDate start = LocalDate.of(2023, 5, 1); // 周一 LocalDate end = LocalDate.of(2023, 5, 10); // 周三 long workingDays = calculateWorkingDays(start, end); System.out.printf("%s 到 %s 之间有 %d 个工作日%n", start, end, workingDays); } } 5.3 计算账单周期和到期日 import java.time.LocalDate; import java.time.YearMonth; import java.time.format.DateTimeFormatter; public class BillingCycleCalculator { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); /** * 计算下一个账单日 */ public static LocalDate calculateNextBillingDate(LocalDate currentDate, int billingDay) { YearMonth currentYearMonth = YearMonth.from(currentDate); LocalDate billingDate = currentYearMonth.atDay(billingDay); if (currentDate.isAfter(billingDate)) { // 如果当前日期已经过了本月账单日,则计算下月 return currentYearMonth.plusMonths(1).atDay(billingDay); } return billingDate; } /** * 计算账单周期 */ public static String calculateBillingPeriod(LocalDate billingDate, int cycleMonths) { LocalDate startDate = billingDate.minusMonths(cycleMonths); return String.format("%s 至 %s", startDate.format(FORMATTER), billingDate.format(FORMATTER)); } /** * 计算宽限期结束日 */ public static LocalDate calculateGracePeriodEnd(LocalDate billingDate, int graceDays) { return billingDate.plusDays(graceDays); } public static void main(String[] args) { LocalDate today = LocalDate.of(2023, 5, 15); int billingDay = 10; // 每月10日出账 LocalDate nextBilling = calculateNextBillingDate(today, billingDay); System.out.println("下一个账单日: " + nextBilling); String period = calculateBillingPeriod(nextBilling, 1); System.out.println("账单周期: " + period); LocalDate graceEnd = calculateGracePeriodEnd(nextBilling, 20); System.out.println("宽限期结束: " + graceEnd); } } 5.4 生成日期范围序列 import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class DateRangeGenerator { /** * 生成两个日期之间的所有日期 */ public static List generateDateRange(LocalDate start, LocalDate end) {
List dates = new ArrayList<>();
LocalDate current = start;

while (!current.isAfter(end)) {
dates.add(current);
current = current.plusDays(1);
}

return dates;
}

/**
* 生成两个日期之间的所有工作日
*/
public static List generateWorkingDays(LocalDate start, LocalDate end) {
return generateDateRange(start, end).stream()
.filter(date -> {
DayOfWeek day = date.getDayOfWeek();
return day != DayOfWeek.SATURDAY && day != DayOfWeek.SUNDAY;
})
.collect(Collectors.toList());
}

/**
* 生成两个日期之间的所有月份
*/
public static List generateMonthRange(LocalDate start, LocalDate end) {
List months = new ArrayList<>();
YearMonth current = YearMonth.from(start);
YearMonth endMonth = YearMonth.from(end);

while (!current.isAfter(endMonth)) {
months.add(current);
current = current.plusMonths(1);
}

return months;
}

/**
* 使用Java 8 Stream API生成日期范围
*/
public static List generateDateRangeStream(LocalDate start, LocalDate end) {
return Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1)
.collect(Collectors.toList());
}

public static void main(String[] args) {
LocalDate start = LocalDate.of(2023, 5, 1);
LocalDate end = LocalDate.of(2023, 5, 7);

// 生成所有日期
List allDates = generateDateRange(start, end);
System.out.println(“所有日期: ” + allDates);

// 生成工作日
List workingDays = generateWorkingDays(start, end);
System.out.println(“工作日: ” + workingDays);

// 生成月份范围
List months = generateMonthRange(
LocalDate.of(2023, 1, 15),
LocalDate.of(2023, 6, 20)
);
System.out.println(“月份范围: ” + months);

// Stream API方式
List streamDates = generateDateRangeStream(start, end);
System.out.println(“Stream生成: ” + streamDates);
}
}
六、与旧API的互操作
6.1 java.util.Date ↔ java.time
import java.time.*;
import java.util.Date;

public class DateConversion {
public static void main(String[] args) {
// 1. Date → Instant → java.time
Date legacyDate = new Date();
Instant instant = legacyDate.toInstant();

// 转换为不同精度
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

System.out.println(“Legacy Date: ” + legacyDate);
System.out.println(“Instant: ” + instant);
System.out.println(“LocalDateTime: ” + ldt);
System.out.println(“ZonedDateTime: ” + zdt);

// 2. java.time → Date
LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();

// 转换为Date
Date dateFromLocalDate = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
Date dateFromLocalDateTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
Date dateFromZonedDateTime = Date.from(zonedDateTime.toInstant());

System.out.println(“\nDate from LocalDate: ” + dateFromLocalDate);
System.out.println(“Date from LocalDateTime: ” + dateFromLocalDateTime);
Date fromZonedDateTime: ” + dateFromZonedDateTime);
}
}
6.2 java.util.Calendar ↔ java.time
import java.time.*;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarConversion {
public static void main(String[] args) {
// Calendar → java.time
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.MAY, 15, 10, 30, 0); // 月份从0开始!

// 转换为Instant
Instant instant = calendar.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

System.out.println(“Calendar: ” + calendar.getTime());
System.out.println(“ZonedDateTime: ” + zdt);

// java.time → Calendar
LocalDate date = LocalDate.of(2023, 5, 15);
LocalTime time = LocalTime.of(10, 30);
LocalDateTime dateTime = LocalDateTime.of(date, time);

// 使用GregorianCalendar
GregorianCalendar gregorianCalendar = GregorianCalendar.from(
dateTime.atZone(ZoneId.systemDefault())
);

System.out.println(“\nGregorianCalendar: ” + gregorianCalendar.getTime());

// 精确转换
ZonedDateTime zdt2 = ZonedDateTime.of(2023, 5, 15, 10, 30, 0, 0, ZoneId.systemDefault());
Calendar cal2 = GregorianCalendar.from(zdt2);
System.out.println(“精确转换: ” + cal2.getTime());
}
}
6.3 处理时间戳(Timestamp)
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class TimestampConversion {
public static void main(String[] args) {
// Timestamp → java.time
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Instant instant = timestamp.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

System.out.println(“Timestamp: ” + timestamp);
System.out.println(“Instant: ” + instant);
System.out.println(“LocalDateTime: ” + ldt);

// java.time → Timestamp
LocalDateTime now = LocalDateTime.now();
Instant instant2 = now.atZone(ZoneId.systemDefault()).toInstant();
Timestamp timestamp2 = Timestamp.from(instant2);

System.out.println(“\nLocalDateTime: ” + now);
System3.println(“Timestamp: ” + timestamp2);

// 处理纳秒精度
Timestamp tsWithNanos = new Timestamp(System.currentTimeMillis());
tsWithNanos.setNanos(123456789);
Instant instant3 = tsWithNanos.toInstant();
System.out.println(“\n带纳秒的Timestamp: ” + tsWithNanos);
System.out.println(“Instant纳秒: ” + instant3.getNano());
}
}
七、最佳实践总结
7.1 选择合适的日期时间类
场景
推荐类
原因
只需要日期(生日、账单日)
LocalDate
轻量、清晰
需要日期+时间(日志、交易)
LocalDateTime
精确到秒
需要时区(国际化应用)
ZonedDateTime
支持时区转换
时间间隔计算
Duration
基于时间单位
日期间隔计算
Period
基于日历单位
时间戳存储
Instant
机器时间
7.2 始终使用不可变对象
// 不好:可变对象
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1); // 修改原对象

// 好:不可变对象
LocalDate date = LocalDate.now();
LocalDate tomorrow = date.plusDays(1); // 返回新对象
7.3 明确时区
// 不好:依赖系统默认时区
LocalDateTime now = LocalDateTime.now();

// 好:明确指定时区
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(“Asia/Shanghai”));
7.4 使用try-with-resources处理资源
// 对于需要关闭的资源(如DateTimeFormatterBuilder)
// 虽然DateTimeFormatter不需要关闭,但类似模式适用于其他资源
7.5 避免使用旧API
除非必须与遗留代码交互,否则完全避免使用
java.util.Date
和
java.util.Calendar
。
7.6 单元测试日期逻辑
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;

public class DateLogicTest {
@Test
public void testAddWorkingDays() {
LocalDate start = LocalDate.of(2023, 5, 1); // 周一
LocalDate expected = LocalDate.of(2023, 5, 8); // 下周一
LocalDate actual = WorkingDayCalculator.addWorkingDays(start, 5);
assertEquals(expected, actual);
}

@Test
public void testMonthEndHandling() {
LocalDate jan31 = LocalDate.of(2023, 1, 31);
LocalDate feb28 = jan31.plusMonths(1);
assertEquals(LocalDate.of(2023, 2, 28), feb28);
}
}
八、总结
Java日期时间处理虽然复杂,但通过掌握
java.time
包的核心概念和最佳实践,可以避免大多数常见陷阱。关键要点:
优先使用Java 8的java.time包
,避免使用旧API
根据场景选择合适的类
:
LocalDate
、
LocalDateTime
、
ZonedDateTime
始终考虑时区
,特别是在国际化应用中
理解Period和Duration的区别
:前者基于日历,后者基于时间
小心月末和闰年
,使用
YearMonth
处理月份计算
注意夏令时
,使用
ZonedDateTime
而非
LocalDateTime
保持不可变性
,确保线程安全
编写单元测试
,验证日期计算逻辑
通过本文的详细示例和最佳实践,你应该能够自信地处理Java中的各种日期加减场景,编写出健壮、高效的日期时间代码。记住,良好的日期时间处理是高质量软件的基础。