Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java.time.Period#normalized() not normalize days?

In the Java class java.time.Period the method normalized() has the following in its Javadoc:

This normalizes the years and months units, leaving the days unit unchanged.

The superclass' method has the following in its Javadoc:

The process of normalization is specific to each calendar system. For example, in the ISO calendar system, the years and months are normalized but the days are not, [...]

I do not have access to the actual text of ISO 8601-1:2019, and would not like to spend hundreds of [insert currency here]s on it (my guess is that normalization may be described in Part 1: Basic rules and not in Part 2: Extensions).

Could someone shed light upon why Period#normalized() does not normalize days? Does it really come directly from ISO 8601 itself, is it somewhere else specified, or is it just specific to the Java implementation?

like image 254
D. Kovács Avatar asked Feb 04 '23 18:02

D. Kovács


1 Answers

This is because a period of years or months is always the same amount of time (the same period) for any given date. A year is always 12 months, 12 months are always a year, thus these parts of the period can easily be normalized.

However days are variable in relation to months and years. If you have a period of 1 year, 1 month and 32 days, you cannot normalize this to 1 year, 2 months and then a fixed amount of days, because it might be 1 day, 2 days, 3 days or 4 days, depending on which date you will apply the period on.

A month can be 28, 29, 30 or 31 days. A year can be 365 or 366 days. And since a period is independent of any fixed date, there is no way to decide these relations.

Example:

2019-01-01 + 01-01-32 is 2020-03-04

2020-01-01 + 01-01-32 is 2021-03-03

2020-02-01 + 01-01-32 is 2021-04-02

2020-03-01 + 01-01-32 is 2021-05-03

As you can see the days resulting from applying the same period to different dates varies depending on the month and on if it's a leap year.

Thus it is impossible to normalize days in a period and the days are not touched when normalizing.

like image 114
Max Vollmer Avatar answered Feb 06 '23 11:02

Max Vollmer