Reputation: 109
My problem is to find a useful method from the Temporal interface. In specific, I want to have the year from an Object, which is implementing the Temporal interface. All methods of the interface just add or sub from the objects, however, I just want to get the year of the Temporal itself.
Upvotes: 3
Views: 1775
Reputation: 5794
The Temporal
interface inherits the TemporalAccessor::get
method, so for example you can do this:
Temporal t = LocalDate.now();
System.out.println(t.get(ChronoField.YEAR));
Output:
2018
EDIT
As @Ole V.V. pointed out is good to validate if the Temporal
implementation supports the desired field using Temporal::isSupported
:
if(t.isSupported(ChronoField.YEAR)){
// ...
}
This will prevent getting exceptions if the Temporal
implementation doesn't support the desired field. For example, Instant
is a Temporal
implementation that doesn't support the Year.
Upvotes: 5
Reputation: 1199
its defined in its superInterface TemporalAccessor
.
so you can get the year by,
int year = temporal.get(ChronoField.YEAR);
Upvotes: 3