Java Reference
In-Depth Information
12.1.4. Defining a Duration or a Period
All the classes you've seen so far implement the Temporal interface, which defines how to read
and manipulate the values of an object modeling a generic point in time. We've shown you a few
ways to create different Temporal instances. The next natural step is to create a duration
between two temporal objects. The between static factory method of the Duration class serves
exactly this purpose. You can create a duration between two LocalTimes, two LocalDateTimes,
or two Instants as follows:
Duration d1 = Duration.between(time1, time2);
Duration d1 = Duration.between(dateTime1, dateTime2);
Duration d2 = Duration.between(instant1, instant2);
Because LocalDateTime and Instant are made for different purposes, one to be used by humans
and the other by machines, you're not allowed to mix them. If you try to create a duration
between them, you'll only obtain a DateTimeException. Moreover, because the Duration class is
used to represent an amount of time measured in seconds and eventually nanoseconds, you
can't pass a LocalDate to the between method.
When you need to model an amount of time in terms of years, months, and days, you can use
the Period class. You can find out the difference between two LocalDates with the between
factory method of that class:
Period tenDays = Period.between(LocalDate.of(2014, 3, 8),
LocalDate.of(2014, 3, 18));
Finally, both the Duration and Period classes have other convenient factory methods to create
instances of them directly, in other words, without defining them as the difference between two
temporal objects, as shown in the next listing.
Listing 12.5. Creating Duration s and Period s
Duration threeMinutes = Duration.ofMinutes(3);
Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
Period tenDays = Period.ofDays(10);
Period threeWeeks = Period.ofWeeks(3);
Period twoYearsSixMonthsOneDay = Period.of(2, 6, 1);
 
Search WWH ::




Custom Search