brick / date-time

Date and time library for PHP
MIT License
323 stars 29 forks source link

Add LocalDateRange::toPeriod #51

Closed BenMorel closed 2 years ago

BenMorel commented 2 years ago

Following #48, in addition to LocalDateRange::getDuration, it would be useful to add a LocalDateRange::toPeriod() method.

There are several ways to implement this method. Take for example 2021-03-28/2022-04-01, we can represent it as either:

Not sure which one we should choose here. The first one has a negative part for a non-negative range, so is probably not that intuitive; the third one is probably not what you would expect either, and one may argue that if you just want a raw number of days, you may use getDuration() instead. So at first glance, I'd go with the second option.

Another solution could be to offer several methods, but this can add to confusion.

I can see that Java's threeten-extra has a [toPeriod](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/LocalDateRange.html#toPeriod()) method, it would be nice to see which way they followed.

Cc @solodkiy

solodkiy commented 2 years ago

I am not really fan of this Period concept. Never used it in my production. I personally could imagine use of convert 2021-03-28/2022-04-01 to Period 369 days, but 1 year, 0 month, 4 days.. what should we use it for?

BenMorel commented 2 years ago

Period is definitely useful to represent something like +6 months, that you cannot represent with a Duration, that only works with days.

In the case of LocalDateRange::toPeriod(), one use case I can think of is for display purposes, for example to display a person's age, in which case I think 1 year and 4 days is what you would expect here.

BenMorel commented 2 years ago

Just tried it on Java, the output of the example above is P1Y4D, that is, 1 year and 4 days :+1:

And the implementation just uses Period::between(), which we have already implemented, so the implementation will be trivial.

BenMorel commented 2 years ago

Implemented in 213a4ba7184d983dfe2087658b68eea7140d009f.