Java Convert Years to Period
Tags: Java Period Java 8
In this Java core tutorial we learn how to convert a number of years to java.time.Period object in Java programming language.
How to convert years to Period in Java
In Java, we can use the Period.ofYears(int years) static method to instantiate a new Period object from number of years as the example Java code below.
ConvertYearsPeriodExample1.java
import java.time.Period;
public class ConvertYearsPeriodExample1 {
public static void main(String... args) {
int numberOfYears = 5;
Period period = Period.ofYears(numberOfYears);
System.out.println("Number of years: " + numberOfYears);
System.out.println("Period: " + period);
}
}
Number of years: 5
Period: P5Y
Happy Coding 😊