高级时间操作
时间段和持续时间计算
flowchart TD
A[时间操作] --> B[时间段]
A --> C[持续时间]
A --> D[时间调整器]
时间段操作
import java.time.LocalDate;
import java.time.Period;
public class PeriodDemo {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2024, 6, 15);
// 计算两个日期之间的时间段
Period period = Period.between(startDate, endDate);
System.out.println("年数: " + period.getYears());
System.out.println("月数: " + period.getMonths());
System.out.println("天数: " + period.getDays());
}
}
持续时间计算
import java.time.LocalDateTime;
import java.time.Duration;
public class DurationDemo {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.now();
LocalDateTime end = start.plusHours(5).plusMinutes(30);
Duration duration = Duration.between(start, end);
System.out.println("小时数: " + duration.toHours());
System.out.println("分钟数: " + duration.toMinutes());
}
}
时间调整器
调整器 |
描述 |
示例 |
firstDayOfMonth() |
当前月的第一天 |
date.with(TemporalAdjusters.firstDayOfMonth()) |
lastDayOfYear() |
当前年的最后一天 |
date.with(TemporalAdjusters.lastDayOfYear()) |
nextOrSame() |
下一个或同一天的指定星期几 |
date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY)) |
自定义时间调整器
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class CustomTemporalAdjusterDemo {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
// 内置调整器
LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
// 自定义调整器
TemporalAdjuster nextWorkingDay = temporal -> {
LocalDate date = LocalDate.from(temporal);
do {
date = date.plusDays(1);
} while (date.getDayOfWeek().getValue() > 5);
return date;
};
LocalDate workingDay = today.with(nextWorkingDay);
}
}
时区转换
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class ZoneConversionDemo {
public static void main(String[] args) {
ZonedDateTime newYorkTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
// 转换为东京时间
ZonedDateTime tokyoTime = newYorkTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
System.out.println("纽约时间: " + newYorkTime);
System.out.println("东京时间: " + tokyoTime);
}
}
格式化与解析
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormattingDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// 自定义格式化器
DateTimeFormatter customFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(customFormatter);
LocalDateTime parsedDate = LocalDateTime.parse(formattedDate, customFormatter);
}
}
性能与最佳实践
- 使用不可变的时间类
- 简单场景下优先使用
LocalDate/LocalTime
- 谨慎处理时区
- 使用合适的格式化器
LabEx建议
LabEx提供全面的教程和实践实验室,帮助你掌握Java中的高级时间操作技术,助力开发人员构建健壮的时间处理应用程序。