java如何计算时间
计算时间差
使用java.time包中的类可以轻松计算时间差。Duration适用于秒和纳秒级别的时间差,Period适用于年、月、日级别的时间差。
LocalDateTime start = LocalDateTime.of(2023, 1, 1, 10, 0);
LocalDateTime end = LocalDateTime.of(2023, 1, 1, 12, 30);
Duration duration = Duration.between(start, end);
long hours = duration.toHours(); // 结果为2
long minutes = duration.toMinutes() % 60; // 结果为30
日期加减
LocalDate和LocalDateTime类提供了加减时间的方法,支持年、月、日、小时、分钟等单位的操作。
LocalDate date = LocalDate.now();
LocalDate nextWeek = date.plusDays(7);
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime inTwoHours = dateTime.plusHours(2);
格式化时间
DateTimeFormatter类用于格式化和解析日期时间对象,支持自定义模式。
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter); // 如"2023-10-01 15:30:45"
时间戳转换
Instant类用于处理时间戳,可以与LocalDateTime相互转换。
Instant instant = Instant.now(); // 获取当前时间戳
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Instant fromDateTime = dateTime.atZone(ZoneId.systemDefault()).toInstant();
时区处理
ZonedDateTime类用于处理带时区的日期时间,支持不同时区的转换。
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));
ZonedDateTime tokyoTime = zoned.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
获取当前时间
使用LocalDateTime或LocalDate可以获取当前日期时间,无需手动处理时区。
LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
比较时间
LocalDate和LocalDateTime实现了Comparable接口,可以直接比较时间先后。
LocalDate date1 = LocalDate.of(2023, 1, 1);
LocalDate date2 = LocalDate.of(2023, 1, 2);
boolean isBefore = date1.isBefore(date2); // true






