日期和时间 API
Java 时间 API 概述
Java 提供了全面的 API 来处理日期、时间以及与时间相关的操作。java.time
包提供了丰富的类和方法,用于复杂的时间管理。
关键日期和时间 API
1. 解析与格式化
public class DateTimeFormatting {
public static void main(String[] args) {
// 从字符串解析日期
LocalDate parsedDate = LocalDate.parse("2023-06-15");
// 自定义格式化
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = LocalDate.now().format(customFormatter);
System.out.println("格式化后的日期: " + formattedDate);
// 使用自定义格式解析
LocalDate customParsedDate = LocalDate.parse("15/06/2023", customFormatter);
System.out.println("自定义解析后的日期: " + customParsedDate);
}
}
2. 日期计算
public class DateCalculations {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
// 增加天数
LocalDate futureDate = today.plusDays(30);
// 减去月份
LocalDate pastDate = today.minusMonths(2);
// 比较日期
boolean isBefore = today.isBefore(futureDate);
boolean isAfter = today.isAfter(pastDate);
System.out.println("未来日期: " + futureDate);
System.out.println("过去日期: " + pastDate);
System.out.println("是否在未来日期之前: " + isBefore);
System.out.println("是否在过去日期之后: " + isAfter);
}
}
时区操作
graph TD
A[本地时间] --> B[转换为不同时区]
B --> C[带时区的日期时间]
C --> D[Instant]
D --> E[通用时间戳]
时区转换示例
public class TimeZoneOperations {
public static void main(String[] args) {
// 系统默认时区的当前时间
ZonedDateTime systemTime = ZonedDateTime.now();
// 转换为特定时区
ZonedDateTime tokyoTime = systemTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
// 转换为不同时区
ZonedDateTime newYorkTime = systemTime.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("系统时间: " + systemTime);
System.out.println("东京时间: " + tokyoTime);
System.out.println("纽约时间: " + newYorkTime);
}
}
综合 API 比较
API |
使用场景 |
关键方法 |
LocalDate |
没有时间的日期 |
plusDays() , minusMonths() |
LocalTime |
没有日期的时间 |
plusHours() , minusMinutes() |
LocalDateTime |
日期和时间 |
atZone() , toLocalDate() |
ZonedDateTime |
日期、时间和时区 |
withZoneSameInstant() |
Instant |
机器时间戳 |
now() , ofEpochSecond() |
高级时间操作
public class AdvancedTimeManipulation {
public static void main(String[] args) {
// 时间段计算
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
Period period = Period.between(startDate, endDate);
// 持续时间计算
LocalTime startTime = LocalTime.of(10, 0);
LocalTime endTime = LocalTime.of(15, 30);
Duration duration = Duration.between(startTime, endTime);
System.out.println("时间段: " + period);
System.out.println("持续时间: " + duration);
}
}
LabEx 学习提示
LabEx 建议通过交互式编码练习来实践这些 API,以建立肌肉记忆并加深理解。
最佳实践
- 根据特定场景使用适当的时间类
- 在全球应用中始终考虑时区
- 优先使用不可变的时间类
- 使用内置的格式化和解析方法