Java Convert String to Period

Tags: String Java Period Java 8

In this Java core tutorial we learn how to convert a String object to java.time.Period object in Java programming language.

How to convert String to Period in Java

In Java, we can use the Period.parse(CharSequence text) static method to parse a ISO-8601 period formats String to a Period object as the example Java code below.

ConvertStringToPeriodExample1.java

import java.time.Period;

public class ConvertStringToPeriodExample1 {
    public static void main(String... args) {
        // P3Y equals 3 years
        Period period1 = Period.parse("P3Y");

        // P7M equals 7 months
        Period period2 = Period.parse("P7M");

        // P8W equals 8 weeks
        Period period3 = Period.parse("P8W");

        // P6D equals 6 days
        Period period4 = Period.parse("P6D");

        // P1Y2M3D equals 1 year, 2 months, 3 days
        Period period5 = Period.parse("P1Y2M3D");

        // P1Y2M3W4D equals 1 year, 2 months, 3 weeks, 4 days
        Period period6 = Period.parse("P1Y2M3W4D");

        // P-1Y2M equals -1 year, 2 months
        Period period7 = Period.parse("P-1Y2M");

        // -P1Y2M equals -1 year, -2 months
        Period period8 = Period.parse("-P1Y2M");

        System.out.println("period1 (P3Y equals 3 years): " + period1);
        System.out.println("period2 (P7M equals 7 months): " + period2);
        System.out.println("period3 (P8W equals 8 weeks): " + period3);
        System.out.println("period4 (P6D equals 6 days): " + period4);
        System.out.println("period5 (P1Y2M3D equals 1 year, 2 months, 3 days): " + period5);
        System.out.println("period6 (P1Y2M3W4D equals 1 year, 2 months, 3 weeks, 4 days): " + period6);
        System.out.println("period7 (P-1Y2M equals -1 year, 2 months): " + period7);
        System.out.println("period8 (-P1Y2M equals -1 year, -2 months): " + period8);
    }
}
The output as below.
period1 (P3Y equals 3 years): P3Y
period2 (P7M equals 7 months): P7M
period3 (P8W equals 8 weeks): P56D
period4 (P6D equals 6 days): P6D
period5 (P1Y2M3D equals 1 year, 2 months, 3 days): P1Y2M3D
period6 (P1Y2M3W4D equals 1 year, 2 months, 3 weeks, 4 days): P1Y2M25D
period7 (P-1Y2M equals -1 year, 2 months): P-1Y2M
period8 (-P1Y2M equals -1 year, -2 months): P-1Y-2M

Happy Coding 😊

Java Convert Years to Period

Java Convert Months to Period

Java Convert Weeks to Period

Java Convert Days to Period

Java Convert Days Months Years to Period