← 中文资源

简体中文版本

Period 与 Duration 的时间跨度

Period.between 按年月日拆分日历跨度,ChronoUnit.DAYS 给出总天数;1 月 31 日加一个月自动收拢到月末,Duration 只量精确经过时间,负跨度可取绝对值。

阅读英文原文

实现要点

从 1 月 31 日到 3 月 15 日,Period.between 产出 1 个月 15 天——这是日历字段拆分,不是天数。ChronoUnit.DAYS.between 回答另一个问题,对同两个日期打印总天数 43。

月份运算自动收拢:start.plusMonths(1) 把 1 月 31 日变成 2 月 28 日而不是抛异常。Duration 处理 Instant,没有日历概念——1h30m45s 打印 5445 秒与 90 分钟,反向跨度用 abs 恢复,同样打印 90。

细节提醒

  • 2026 不是闰年,收拢落在 2 月 28 日。
  • Duration.getSeconds 与 toSeconds 在这里等价,前者更老。

核心语句

System.out.println("one month later=" + start.plusMonths(1));

代码示例

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class TimeSpans {

    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 31);
        LocalDate end = LocalDate.of(2026, 3, 15);

        // Period.between splits the span into calendar fields: years/months/days
        Period calendar = Period.between(start, end);
        System.out.println("months=" + calendar.getMonths() + " days=" + calendar.getDays());

        // ChronoUnit.DAYS reports only the total day count
        System.out.println("total days=" + ChronoUnit.DAYS.between(start, end));

        // adding one month: Jan 31 overflows and clamps to the last day of February
        System.out.println("one month later=" + start.plusMonths(1));

        // Duration measures precise elapsed time, with no calendar notion
        Duration span = Duration.between(
                Instant.parse("2026-11-21T00:00:00Z"),
                Instant.parse("2026-11-21T01:30:45Z"));
        System.out.println("seconds=" + span.getSeconds());
        System.out.println("minutes=" + span.toMinutes());

        // a reversed span can be made positive with abs
        Duration reversed = Duration.between(
                Instant.parse("2026-11-21T01:30:45Z"),
                Instant.parse("2026-11-21T00:00:00Z"));
        System.out.println("abs minutes=" + reversed.abs().toMinutes());
    }
}