The Period
class in java.time handles only the date-oriented potion: years, months, days.
What about the time portion: hours, minutes, seconds?
How can we parse and generate string representations of full periods as defined in ISO 8601, PnYnMnDTnHnMnS
? For example, a day and a half: P1DT12H
. The academic year is nine months, P9M
. Every year I get two weeks and 3 days of vacation, P17D
. The customer occupied the hotel room for 2 days and seventeen and a half hours, P2DT17H30M
.
The Period
class in Joda-Time handles full period. Why not in java.time? Is there some other mechanism?
Java Date Time - Duration toString() exampleDuration toString() returns a string representation of this duration using ISO-8601 seconds based representation, such as PT8H6M12. 345S. The format of the string will be PTnHnMnS , where n is the relevant hours, minutes or seconds part of the duration.
The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days.
The equals() method of Period class in Java is used to check if two given periods are equal or not. The comparison is based on the type Period and each of the three years, months and date. To be equal, all of the three year, month and date must be individually equal.
In Java SE 8, it is the responsibility of the application to create a class linking Period
and Duration
if that is needed.
Note that a Duration
contains an amount of seconds, not separate amounts of seconds, minutes and hours. The amount of seconds can exceed 24 hours, thus a Duration
can represent a "day". But it is a fixed 24 hours day. By contrast, the representation of a "day in Period
is descriptive and takes into account DST. The state of a Period
is formed from three separate fields - days, months and years.
Bear in mind that "The customer occupied the hotel room for 2 days and seventeen and a half hours, P2DT17H30M" has the possibility to be complicated by DST cutovers. Using Period
and Duration
separately things are clear - Period
is affected by DST cutovers and Duration
is not.
In design terms, the original java.time Period
did include hours, minutes and seconds. However, this resulted in the need for many methods and complicated Javadoc to describe all the possibilities around normalization and DST. By separating the concepts, the interaction of each with the timeline is a lot clearer. Note that the two classes also relate to the SQL design ("year to month" and "day to second" concepts).
There are no current plans to add a new class for Java SE 9in this area, however it cannot be completely ruled out because XML/ISO-8601 allows a single combined representation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With