Close

Java Date Time - Period.get() Examples

Java Date Time Java Java API 


Class:

java.time.Period

java.lang.Objectjava.lang.Objectjava.time.Periodjava.time.Periodjava.time.chrono.ChronoPeriodChronoPeriodjava.io.SerializableSerializableLogicBig

Method:

public long get(TemporalUnit unit)

This method returns the value of the requested unit from this Period object.


Examples


package com.logicbig.example.period;

import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;

public class GetExample {

public static void main(String... args) {
Period p = Period.of(100, 10, 20);
System.out.println(p);

for (ChronoUnit unit : ChronoUnit.values()) {
try {
long l = p.get(unit);
System.out.printf("%6s > %s%n", unit, l);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf(" -- %s not supported.%n", unit);
}
}
}
}

Output

P100Y10M20D
-- Nanos not supported.
-- Micros not supported.
-- Millis not supported.
-- Seconds not supported.
-- Minutes not supported.
-- Hours not supported.
-- HalfDays not supported.
Days > 20
-- Weeks not supported.
Months > 10
Years > 100
-- Decades not supported.
-- Centuries not supported.
-- Millennia not supported.
-- Eras not supported.
-- Forever not supported.




package com.logicbig.example.period;

import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;

public class GetExample2 {

public static void main(String... args) {
Period p = Period.ofDays(2);
System.out.println(p);

for (ChronoUnit unit : ChronoUnit.values()) {
try {
long l = p.get(unit);
System.out.printf("%6s > %s%n", unit, l);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf(" -- %s not supported.%n", unit);
}
}
}
}

Output

P2D
-- Nanos not supported.
-- Micros not supported.
-- Millis not supported.
-- Seconds not supported.
-- Minutes not supported.
-- Hours not supported.
-- HalfDays not supported.
Days > 2
-- Weeks not supported.
Months > 0
Years > 0
-- Decades not supported.
-- Centuries not supported.
-- Millennia not supported.
-- Eras not supported.
-- Forever not supported.




See Also