briannesbitt / Carbon

A simple PHP API extension for DateTime.
https://carbon.nesbot.com/
MIT License
16.53k stars 1.28k forks source link

How to get format in days hours minutes seconds in setCascadeFactors function? #2921

Closed vipera7 closed 7 months ago

vipera7 commented 7 months ago

Hello,

I encountered an issue with the following code:

use Carbon\CarbonInterval;

CarbonInterval::setCascadeFactors([
    'minute' => [60, 'seconds'],
    'hour' => [60, 'minutes'],
    'day' => [24, 'hours']
]);

echo CarbonInterval::fromString('3w 18d 53h 159m')->cascade()->forHumans();

Carbon version: 2.72.1

PHP version: 8.2.13 (from https://play.phpsandbox.io)

I expected to get:

41 days 7 hours 39 minutes

But I actually get:

5 weeks 6 days 7 hours 39 minutes

Thanks!

kylekatarnls commented 7 months ago

Hello,

You can skip any units you don't want in the forHumans() options:

echo CarbonInterval::fromString('3w 18d 53h 159m')->cascade()->forHumans([
    'skip' => ['week', 'month', 'year'],
]);

Output your expected string:

41 days 7 hours 39 minutes