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);
    }
}
The output as below.
Number of years: 5
Period: P5Y

Happy Coding 😊

Java Convert Months to Period

Java Convert Weeks to Period

Java Convert Days to Period

Java Convert Days Months Years to Period

Java Convert String to Period