Period and Duration in Java – Java中的周期和持续时间

最后修改: 2017年 5月 7日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to take a look at two new classes for working with dates introduced in Java 8: Period and Duration.

在这个快速教程中,我们将看看Java 8中引入的两个用于处理日期的新类:PeriodDuration

Both classes can be used to represent an amount of time or determine the difference between two dates. The main distinction between the two classes is that Period uses date-based values, while Duration uses time-based values.

这两个类都可以用来表示一个时间量或确定两个日期之间的差异。这两个类的主要区别是:Period使用基于日期的值,而Duration使用基于时间的值。

2. Period Class

2.

The Period class uses the units year, month and day to represent a period of time.

Period类使用单位年、月、日来表示一个时间段。

We can obtain a Period object as the difference between two dates by using the between() method:

我们可以通过使用between()方法获得一个Period对象作为两个日期的差值。

LocalDate startDate = LocalDate.of(2015, 2, 20);
LocalDate endDate = LocalDate.of(2017, 1, 15);

Period period = Period.between(startDate, endDate);

Then, we can determine the date units of the period using the methods getYears(), getMonths(), getDays():

然后,我们可以使用getYears(), getMonths(), getDays()方法来确定该时期的日期单位。

LOG.info("Years:" + period.getYears() + 
  " months:" + period.getMonths() + 
  " days:"+period.getDays());

In this case, the isNegative() method, which returns true if any of the units are negative, can be used to determine if the endDate is higher than the startDate:

在这种情况下, isNegative()方法(如果任何单位为负数,则返回true)可以用来确定endDate是否高于startDate

assertFalse(period.isNegative());

If isNegative() returns false, then the startDate is earlier than the endDate value.

如果isNegative()返回false,那么startDate就比endDate值早。

Another way to create a Period object is based on the number of days, months, weeks or years using dedicated methods:

另一种创建Period对象的方式是基于天数、月数、周数或年数,使用专用方法。

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);

assertEquals(280, fromWeeks.getDays());

If only one of the values is present, for example by using the ofDays() method, then the value of the other units is 0.

如果只有其中一个值,例如通过使用ofDays()方法,那么其他单位的值就是0。

In the case of the ofWeeks() method, the parameter value is used to set the number of days by multiplying it by 7.

ofWeeks()方法的情况下,参数值通过乘以7来设定天数。

We can also create a Period object by parsing a text sequence, which has to have the format “PnYnMnD”:

我们也可以通过解析一个文本序列来创建一个Period对象,其格式必须是 “PnYnMnD”。

Period fromCharYears = Period.parse("P2Y");
assertEquals(2, fromCharYears.getYears());

Period fromCharUnits = Period.parse("P2Y3M5D");
assertEquals(5, fromCharUnits.getDays());

The value of the period can be increased or decreased by using methods of the form plusX() and minusX(), where X represents the date unit:

通过使用plusX()minusX()形式的方法可以增加或减少周期值,其中X代表日期单位。

assertEquals(56, period.plusDays(50).getDays());
assertEquals(9, period.minusMonths(2).getMonths());

3. Duration Class

3.Duration Class

The Duration class represents an interval of time in seconds or nanoseconds and is most suited for handling shorter amounts of time, in cases that require more precision.

Duration类表示以秒或纳秒为单位的时间间隔,最适合在需要更精确的情况下处理较短的时间量。

We can determine the difference between two instants as a Duration object using the between() method:

我们可以使用 between()方法来确定两个瞬间的差异,作为一个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);

Then we can use the getSeconds() or getNanoseconds() methods to determine the value of the time units:

然后我们可以使用getSeconds()getNanoseconds()方法来确定时间单位的值。

assertEquals(60, duration.getSeconds());

Alternatively, we can obtain a Duration instance from two LocalDateTime instances:

另外,我们可以从两个LocalDateTime实例中获得一个Duration实例。

LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);

Duration.between(start, end).getSeconds();

The isNegative() method can be used to verify if the end instant is higher than the start instant:

isNegative()方法可以用来验证结束时刻是否高于开始时刻。

assertFalse(duration.isNegative());

We can also obtain a Duration object based on several time units, using the methods ofDays(), ofHours(), ofMillis(), ofMinutes(), ofNanos(), ofSeconds():

我们还可以使用ofDays(), ofHours(), ofMillis(), ofMinutes(), ofNanos(), ofSeconds()方法,基于多个时间单位获得一个Duration对象。

Duration fromDays = Duration.ofDays(1);
assertEquals(86400, fromDays.getSeconds());
       
Duration fromMinutes = Duration.ofMinutes(60);

To create a Duration object based on a text sequence, this has to be of the form “PnDTnHnMn.nS”:

要创建一个基于文本序列的Duration对象,它必须是 “PnDTnHnMn.nS “的形式。

Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");

A duration can be converted to other time units using toDays(), toHours(), toMillis(), toMinutes():

一个持续时间可以通过toDays(), toHours(), toMillis(), toMinutes()转换为其他时间单位

assertEquals(1, fromMinutes.toHours());

A duration value can be increased or decreased by using methods of the form plusX() or minusX(), where X can stand for days, hours, millis, minutes, nanos or seconds:

通过使用plusX()minusX()形式的方法可以增加或减少一个持续时间值,其中X可以代表天、小时、毫秒、分钟、纳米或秒。

assertEquals(120, duration.plusSeconds(60).getSeconds());     
assertEquals(30, duration.minusSeconds(30).getSeconds());

We can also use the plus() and minus() methods with a parameter that specifies the TemporalUnit to add or subtract:

我们还可以使用 plus()minus()方法,该方法的参数指定了要添加或减少的TemporalUnit

assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());     
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());

4. Conclusion

4.总结

In this tutorial, we’ve shown how we can use the Period and Duration classes.

在本教程中,我们已经展示了如何使用PeriodDuration类。

As always, the full source code of the examples can be found over on GitHub.

一如既往,可以在GitHub上找到这些例子的完整源代码