phpphp-carbon

Month equivalence and unit restriction in forHumans function


I'm encountering two peculiar behaviors with a library, and my objective is to convert seconds into a readable format displaying days, hours, minutes, and seconds.

When attempting to convert 2698447 seconds into a human-readable format using the Carbon library, I obtain the following result:

<?php

use Carbon\CarbonInterval;
use Carbon\Carbon;

echo CarbonInterval::seconds(2698447)->cascade()->forHumans();

enter image description here

However, when using an online converter, the output is different (https://www.tools4noobs.com/online_tools/seconds_to_hh_mm_ss/):

Online Converter Result

In my code, I also experimented with CarbonInterval, and when converting 28 days and 30 days separately, the output seems to imply that 28 days is equivalent to a month:

use Carbon\CarbonInterval;
use Carbon\Carbon;

echo CarbonInterval::seconds(28*24*3600)->cascade()->forHumans(); // Outputs: 28 days
echo "\n";
echo CarbonInterval::seconds(30*24*3600)->cascade()->forHumans(); // Outputs: 30 days
echo "\n";

CarbonInterval Results

Considering these results, I am puzzled about the interpretation of days as a month. How can I configure the conversion to consider a month as 30 or 31 days, and furthermore, is it possible to restrict the output to days as the maximum unit (days hours minutes seconds)?


Solution

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

    echo CarbonInterval::seconds(2698447)->cascade()->forHumans([
        'skip' => ['week', 'month', 'year'],
    ]);