created: 2022-07-24T14:11:32+08:00
updated: 2022-07-24T14:27:43+08:00
tags:
- DateTimeAPI
- DateTimeAPI/Duration
- DateTimeAPI/TemporalUnit/ChronoUnit
- DateTimeAPI/Period
Period and Duration
当你要指定一段时间时,使用最能满足您需求的类或方法:Duration
类、Period
类或 ChronoUnit.between()
方法。Duration
使用基于时间的值(秒、纳秒)测量时间量。 Period
使用基于日期的值(年、月、日)。
Note: A Duration of one day is exactly 24 hours long. A Period of one day, when added to a ZonedDateTime, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.
Duration
Duration
最适合测量基于机器的时间的情况,例如使用 Instant
对象的代码。Duration
对象以秒或纳秒为单位进行测量,并且不使用基于日期的构造,例如年、月和日,尽管该类提供了转换为日、小时和分钟的方法。如果 Duration
的结束点在开始点之前创建,则 Duration
可以具有负值。
example1
Instant t1 = ...;
Instant t2 = ...;
long ns = Duration.between(t1, t2).toNanos();
example2
Instant start= ...;
Duration gap = Duration.ofSeconds(10);
Instant later = start.plus(gap);
Duration
未连接到时间线,因为它不跟踪时区或夏令时。将相当于 1 天的 Duration
添加到 ZonedDateTime
会导致正好添加 24 小时,而不管夏令时或可能导致的其他时差。
ChronoUnit
当您只想测量单个时间单位(例如天或秒)中的时间量时,ChronoUnit.between()
方法很有用。 between()
方法适用于所有基于时间的对象,但它仅返回单个单位的数量。以下代码计算两个时间戳之间的间隔(以毫秒为单位):
Instant previous = ...;
Instant current = ...;
long gap = 0L;
current = Instant.now();
if (previous != null) {
gap = ChronoUnit.MILLIS.between(previous,current);
}
Period
要使用基于日期的值(年、月、日)定义时间量,请使用 Period
类。 Period
类提供了各种get 方法,例如getMonths()
、getDays()
和getYears()
,以便您可以从周期中提取时间量。
总时间段由所有三个单位共同表示:月、日和年。要显示以单个时间单位(例如天)测量的时间量,可以使用 ChronoUnit.between()
方法。
以下代码报告您的年龄,假设您出生于 1960 年 1 月 1 日。Period
类用于确定以年、月和日为单位的时间。使用 ChronoUnit.between()
方法确定相同的时间段,以总天数计,并显示在括号中:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
" months, and " + p.getDays() +
" days old. (" + p2 + " days total)");
result
You are 53 years, 4 months, and 29 days old. (19508 days total)
要计算距离您下一个生日还有多长时间,您可以使用以下代码。 Period
类用于确定以月和日为单位的值。 ChronoUnit.between()
方法返回总天数的值并显示在括号中。
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
LocalDate nextBDay = birthday.withYear(today.getYear());
// If your birthday has occurred this year already, add 1 to the year.
if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) {
nextBDay = nextBDay.plusYears(1);
}
Period p = Period.between(today, nextBDay);
long p2 = ChronoUnit.DAYS.between(today, nextBDay);
System.out.println("There are " + p.getMonths() + " months, and " +
p.getDays() + " days until your next birthday. (" +
p2 + " total)");
result
There are 7 months, and 2 days until your next birthday. (216 total)
这些计算不考虑时区差异。例如,如果您出生在澳大利亚,但目前居住在班加罗尔,这会稍微影响您准确年龄的计算。在这种情况下,将 Period
与 ZonedDateTime
类结合使用。将 Period
添加到 ZonedDateTime
时,会观察到时间差异。
[[Clock]]