brick / date-time

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

Period::getDays() returns only days #11

Closed pupitooo closed 5 years ago

pupitooo commented 5 years ago
// expected
$until = LocalDate::of(2018, 11, 1);
$today = LocalDate::of(2018, 9, 1);
$period = $today->until($until);
$days = $period->getDays(); // 1

$until = LocalDate::of(2018, 11, 1);
$today = LocalDate::of(2018, 9, 1);
$days = $until->toEpochDay() - $today->toEpochDay(); // 62

I miss any funcion to get real days. It's not possible to get real days from Period.

BenMorel commented 5 years ago

Hi, Period cannot return the total number of days, as it depends on the year/month it's applied to.

For example:

Even though your use case is legitimate, it therefore does not belong to Period.

Your approach is the correct one:

$days = $until->toEpochDay() - $today->toEpochDay();

Do you feel like there should be a function such as LocalDate::daysUntil(LocalDate $date) : int?

BenMorel commented 5 years ago

I forgot to mention that this is because until() calculates a period in terms of years, months and days. The alternative would've been to return a Period with only the days set, and zero years and months.

I checked what Java does, and they provide 2 methods:

The first method does the same as the current implementation, but it looks like the second method can be used to get the result in terms of years, months or days individually (as an int, not as a Period, though).

I'm not sure we want to follow this generic route, but I'm not against adding a method like LocalDate::daysUntil(). Thoughts?

The alternative would be to add an optional bool parameter to until(), to allow it to return a Period that only contains days. I'm not sure what this is worth.

pupitooo commented 5 years ago

Just now I am using approach

$days = $until->toEpochDay() - $today->toEpochDay();

but it contains counting in my code. And this is not so easy to use (you have to think about order of items). I preffer LocalDate::daysUntil() because bool parameter switch behaviour of all result. Separated function will be little bit more transparent.

BenMorel commented 5 years ago

Implemented as LocalDate::daysUntil() and released as version 0.1.9!