Java Period.between shows strange output

Viewed 87

I am making an application just for learning purpose. And I tried to calculate the difference between two dates

LocalDate today  = LocalDate.now();
LocalDate localHoudbaarheid = houdbaarheidsDatum;
Period period = Period.between(today, localHoudbaarheid);

The calculation works, but the output is strange.

Output of the code:

Dagen tot over de datum: P9D

The only thing that should be shown is the 9 without the P and D. This is where I call the name period in my code to print it out:

"Dagen tot over de datum: " + period;
3 Answers

There is nothing whatsoever strange about the output, it is exactly what the documentation, i.e. the javadoc of Period.toString() says it is:

Outputs this period as a String, such as P6Y3M1D.

The output will be in the ISO-8601 period format. A zero period will be represented as zero days, 'P0D'.

As documentation says, the output is following the ISO-8601 standard for durations, as also explained on Wikipedia:

Durations define the amount of intervening time in a time interval and are represented by the format P[n]Y[n]M[n]DT[n]H[n]M[n]S ...

  • P is the duration designator (for period) placed at the start of the duration representation.

    • Y is the year designator that follows the value for the number of years.
    • M is the month designator that follows the value for the number of months.
    • W is the week designator that follows the value for the number of weeks.
    • D is the day designator that follows the value for the number of days.

P9D means a Period of 9 Days.

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

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate after9Days = today.plusDays(9);
        Period period = Period.between(today, after9Days);
        System.out.println(period);
        System.out.printf("Years: %d, Months: %d, Days: %d", period.getYears(), period.getMonths(), period.getDays());
    }
}

Output:

P9D
Years: 0, Months: 0, Days: 9

Learn more about it at https://en.wikipedia.org/wiki/ISO_8601#Durations

The toString() method of Period outputs something like:

P(nbYears)Y(nbMonths)M(nbDays)D

P9D means a period of 9 days. P4Y3M9D means a period of 4 years, 3 months, and 9 days.

The Period class has utility methods to get this information: getDays(), getMonths(), and getYears().

If you just want to obtain the difference in the unit you choose, prefer using the until() method on the Temporal interface.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Main {

    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate after3Months9Days = today.plusMonths(3).plusDays(9);
        System.out.println(today.until(after3Months9Days, ChronoUnit.DAYS));
    }
}

This outputs:

101
Related