Java Reference
In-Depth Information
p1: P2Y3M5D
p2: P1Y15M28D
p1.plus(p2): P3Y18M33D
p1.plus(p2).normalized(): P4Y6M33D
p1.minus(p2): P1Y-12M-23D
There is a big difference in the way the Date-Time API treats computations based on periods and durations.
Computations including periods behave the way humans would expect. For example, when you add a period of one
day to a ZonedDateTime , the date component changes to the next day, keeping the time the same, irrespective of how
many hours the day had (23, 24, or 25 hours). However, when you add a duration of a day, it will always add 24 hours.
Let's walk through an example to clarify this.
On 2012-03-11T02:00, the clocks in the US Central time zone were moved forward by one hour, making
2012-03-11 a 23-hour day. Suppose you give a person a datetime of 2012-03-10T07:30 in the US Central time zone. If you
ask him what would be the datetime after a day, his answer would be 2012-03-11T07:30. His answer is natural because,
for humans, adding one day to the current datetime gives the next day with the same time. Let's ask the same question of
a machine. Ask the machine to add 24 hours, which is considered the same as 1 day, to 2012-03-10T07:30. The machine's
response would be 2012-03-11T08:30 because it will add exactly 24 hours to the initial datetime, knowing that the hour
between 02:00 and 03:00 did not exist. Listing 12-11 demonstrates this discussion using a Java program.
Listing 12-11. Difference in Adding a Period and Duration to a Datetime
// PeriodTest.java
package com.jdojo.datetime;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class PeriodTest {
public static void main(String[] args) {
ZoneId usCentral = ZoneId.of("America/Chicago");
LocalDateTime ldt = LocalDateTime.of(2012, Month.MARCH, 10, 7, 30);
ZonedDateTime zdt1 = ZonedDateTime.of(ldt, usCentral);
Period p1 = Period.ofDays(1);
Duration d1 = Duration.ofHours(24);
// Add a period of 1 day and a duration of 24 hours
ZonedDateTime zdt2 = zdt1.plus(p1);
ZonedDateTime zdt3 = zdt1.plus(d1);
System.out.println("Start Datetime: " + zdt1);
System.out.println("After 1 Day period: " + zdt2);
System.out.println("After 24 Hours duration: " + zdt3);
}
}
Search WWH ::




Custom Search