Java 中 Period 和 Duration 的区别

让我搜索有关 Java 中 Period 和 Duration 的相关讨论。

Search

Found 2 results for 'java period duration status:public'

我找到了两个相关的主题,我来帮你阅读一下它们的内容:

Read topic

Reading: Java 中的 Period 和 Duration

根据我的搜索结果,我在论坛上找到了一篇最新的关于 Java 中 Period 和 Duration 的详细解释。让我为你总结一下这两个类的主要区别和用法:

Period 和 Duration 的主要区别

  1. Period

    • 使用基于日期的值(date-based values)
    • 主要用于处理年、月、日的时间段
    • 适用于较长时间段的计算
  2. Duration

    • 使用基于时间的值(time-based values)
    • 主要用于处理秒和纳秒级别的时间
    • 适用于更短、更精确的时间间隔

Period 的主要用法

  1. 创建 Period 对象:
// 通过两个日期之间的差值创建
LocalDate startDate = LocalDate.of(2015, 2, 20);
LocalDate endDate = LocalDate.of(2017, 1, 15);
Period period = Period.between(startDate, endDate);

// 直接创建特定时间段
Period fromUnits = Period.of(3, 10, 10);  // 年、月、日
Period fromDays = Period.ofDays(50);
Period fromMonths = Period.ofMonths(5);
Period fromYears = Period.ofYears(10);
Period fromWeeks = Period.ofWeeks(40);
  1. 解析字符串创建 Period:
Period fromCharYears = Period.parse("P2Y");        // 2年
Period fromCharUnits = Period.parse("P2Y3M5D");    // 2年3月5日

Duration 的主要用法

  1. 创建 Duration 对象:
// 通过两个时间点之间的差值创建
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
Duration duration = Duration.between(start, end);

// 直接创建特定时长
Duration fromDays = Duration.ofDays(1);
Duration fromMinutes = Duration.ofMinutes(60);
  1. Duration 的其他操作:
// 检查 Duration 的性质
duration.isNegative();
duration.isZero();
duration.isPositive();  // Java 18+

// 转换到其他时间单位
duration.toDays();
duration.toHours();
duration.toMillis();
duration.toMinutes();

// 增加或减少时长
duration.plusSeconds(60);
duration.minusSeconds(30);

使用建议

  1. 如果你需要处理年、月、日级别的时间段,使用 Period
  2. 如果你需要更精确的时间计算(包括小时、分钟、秒、纳秒),使用 Duration
  3. Period 可能会损失精度,而 Duration 则保持高精度

这两个类都是在 Java 8 中引入的,属于新的日期时间 API 的一部分,它们提供了更清晰和更易用的时间间隔处理方式。