Java Period and Duration Examples

1. Introduction

In this tutorial, we will explore the usage of Java's Period and Duration APIs with detailed examples. These APIs are part of Java's time library and are crucial for handling precise date and time calculations in Java applications.

Key Points

1. Period is used for measuring a quantity of time in terms of years, months, and days.

2. Duration is used to measure a quantity of time in terms of seconds and nanoseconds.

3. Period can be created from days, from values, from a string, or by calculating the difference between two LocalDate instances.

4. Period instances can be manipulated by adding time units (like years).

5. Period instances can be compared to determine their positivity or negativity, which indicates the direction of time (past or future).

2. Program Steps

1. Create Period instances using various methods, including ofDays, of, and parse.

2. Display Period information derived from different creation methods.

3. Calculate the period between two LocalDate instances using between.

4. Manipulate Period instances by adding years and observing the changes.

5. Compare Period instances to determine the direction of time.

3. Code Program

import java.time.LocalDate;
import java.time.Period;

public class Main {

    public static void main(String[] args) {

        Period fromDays = Period.ofDays(120);
        System.out.println("Period from days: " + fromDays);

        Period periodFromUnits = Period.of(2000, 11, 24);
        System.out.println("Period from units: " + periodFromUnits);

        LocalDate localDate = LocalDate.now();
        Period periodFromLocalDate = Period.of(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth());
        System.out.println("Period from LocalDate: " + periodFromLocalDate);

        Period periodFromString = Period.parse("P2019Y2M25D");
        System.out.println("Period from String: " + periodFromString);

        LocalDate startLocalDate = LocalDate.of(2018, 3, 12);
        LocalDate endLocalDate = LocalDate.of(2019, 7, 20);
        Period periodBetween = Period.between(startLocalDate, endLocalDate);
        System.out.println("\nBetween " + startLocalDate + " and " + endLocalDate + " there are " + periodBetween.getYears() + " year(s)");
        System.out.println("Between " + startLocalDate + " and " + endLocalDate + " there are " + periodBetween.getMonths() + " month(s)");
        System.out.println("Between " + startLocalDate + " and " + endLocalDate + " there are " + periodBetween.getDays() + " days(s)");

        System.out.println("Expressed as y:m:d: " + periodToYMD(periodBetween));

        System.out.println(startLocalDate + " is after " + endLocalDate + " ? " + periodBetween.isNegative());

        Period periodBetweenPlus1Year = periodBetween.plusYears(1L);
        System.out.println("\n" + periodBetween + " has " + periodBetween.getYears() + " year, after adding one year it has " + periodBetweenPlus1Year.getYears());

        Period p1 = Period.ofDays(5);
        Period p2 = Period.ofDays(20);
        Period p1p2 = p1.plus(p2);
        System.out.println(p1 + "+" + p2 + "=" + p1p2);
    }

    private static String periodToYMD(Period period) {
        if (period == null) {
            // or throw IllegalArgumentException
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append(period.getYears())
          .append("y:")
          .append(period.getMonths())
          .append("m:")
          .append(period.getDays())
          .append("d");

        return sb.toString();
    }
}

Output:

Period from days: P120D
Period from units: P2000Y11M24D
Period from LocalDate: P2021Y11M10D
Period from String: P2019Y2M25D
Between 2018-03-12 and 2019-07-20 there are 1 year(s)
Between 2018-03-12 and 2019-07-20 there are 4 month(s)
Between 2018-03-12 and 2019-07-20 there are 8 days(s)
Expressed as y:m:d: 1y:4m:8d
2018-03-12 is after 2019-07-20 ? false
P1Y4M8D has 1 year, after adding one year it has 2
P5D+P20D=P25D

Explanation:

1. Period.ofDays(120) creates a period of 120 days.

2. Period.of(2000, 11, 24) creates a period representing 2000 years, 11 months, and 24 days.

3. Period.of(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth()) creates a period using the current date's year, month, and day values.

4. Period.parse("P2019Y2M25D") parses a string to create a period.

5. Period.between(startLocalDate, endLocalDate) calculates the period between two LocalDate objects.

6. periodBetween.isNegative() checks if the period represents a time in the past (before the start date).

7. periodBetween.plusYears(1) adds one year to the existing period.

8. p1.plus(p2) adds two periods together.


Comments