Java 时间差异计算:Period 和 Duration 的区别及常用 API
Period 和 Duration 是 Java 中用于表示时间的两个类,它们的区别和常用 API 如下:
-
Period:用于表示日期的差异,如两个日期之间的年、月、日差值。
- 创建 Period 对象:可以使用静态方法
Period.of(int years, int months, int days)来创建一个 Period 对象。也可以使用Period.between(LocalDate startDate, LocalDate endDate)来获取两个日期之间的差异。 - 获取差异值:可以使用
getYears()、getMonths()、getDays()方法来获取年、月、日的差异值。
- 创建 Period 对象:可以使用静态方法
-
Duration:用于表示时间的差异,如两个时间点之间的小时、分钟、秒差值。
- 创建 Duration 对象:可以使用静态方法
Duration.ofDays(long days)、Duration.ofHours(long hours)、Duration.ofMinutes(long minutes)、Duration.ofSeconds(long seconds)、Duration.ofMillis(long millis)、Duration.ofNanos(long nanos)来创建 Duration 对象。也可以使用Duration.between(Temporal startInclusive, Temporal endExclusive)来获取两个时间点之间的差异。 - 获取差异值:可以使用
toDays()、toHours()、toMinutes()、toSeconds()、toMillis()、toNanos()方法来获取天、小时、分钟、秒、毫秒、纳秒的差异值。
- 创建 Duration 对象:可以使用静态方法
总结:
- Period 用于表示日期的差异,包含年、月、日的差异值。
- Duration 用于表示时间的差异,包含小时、分钟、秒、毫秒、纳秒的差异值。
- Period 和 Duration 都可以通过静态方法创建对象,也可以使用 between 方法获取差异值。
- Period 和 Duration 都提供了一系列的获取差异值的方法,返回 long 类型的差异值。
示例代码:
LocalDate startDate = LocalDate.of(2021, 1, 1);
LocalDate endDate = LocalDate.of(2021, 12, 31);
Period period = Period.between(startDate, endDate);
System.out.println(period.getYears()); // 输出:0
System.out.println(period.getMonths()); // 输出:11
System.out.println(period.getDays()); // 输出:30
LocalTime startTime = LocalTime.of(10, 30, 0);
LocalTime endTime = LocalTime.of(12, 0, 0);
Duration duration = Duration.between(startTime, endTime);
System.out.println(duration.toHours()); // 输出:1
System.out.println(duration.toMinutes()); // 输出:90
System.out.println(duration.getSeconds()); // 输出:5400
System.out.println(duration.toMillis()); // 输出:5400000
System.out.println(duration.toNanos()); // 输出:5400000000000
以上示例代码演示了如何使用 Period 和 Duration 类来表示日期和时间的差异,并获取差异值。
原文地址: https://www.cveoy.top/t/topic/zu7 著作权归作者所有。请勿转载和采集!