Home » Php » php – How to convert seconds into days hours minutes in Laravel

php – How to convert seconds into days hours minutes in Laravel

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to convert time interval in seconds into days hours minutes. I have tried this.

$value = '90060';
CarbonInterval::seconds($value)->forHumans();

I got the output

90060 seconds

My expected output is

1 day 1 hour 1 minute

How can I get the output using Carbon or CarbonInterval

How to&Answers:

I got a solution.

$value = '90060';
$dt = Carbon::now();
$days = $dt->diffInDays($dt->copy()->addSeconds($value));
$hours = $dt->diffInHours($dt->copy()->addSeconds($value)->subDays($days));
$minutes = $dt->diffInMinutes($dt->copy()->addSeconds($value)->subDays($days)->subHours($hours));
echo CarbonInterval::days($days)->hours($hours)->minutes($minutes)->forHumans();

Updated Solution

CarbonInterval::seconds(90060)->cascade()->forHumans();

Answer:

function dates($value) {
    $s = $ss%60;
    $m = floor(($value %3600)/60);
    $h = floor(($value %86400)/3600);
    $d = floor(($value %2592000)/86400);
    $M = floor($value /2592000);

    return "$M months, $d days, $h hours, $m minutes, $s seconds";
}

Answer:

Try this:

$value = '90060';

        $inAMinute = 60;
        $inAnHour = 60 * $secondsInAMinute;
        $inADay = 24 * $secondsInAnHour;

        $days = floor($value / $inADay);

        $hourSeconds = $value % $inADay;
        $hours = floor($hourSeconds / $inAnHour);

        // Extract minutes
        $minuteSeconds = $hourSeconds % $inAnHour;
        $minutes = floor($minuteSeconds / $inAMinute);


        $timeValues = [];
        $sections = [
            'day' => (int)$days,
            'hour' => (int)$hours,
            'minute' => (int)$minutes,

        ];

        foreach ($sections as $name => $value){
            if ($value > 0){
                $timeValues[] = $value. ' '.$name;
            }
        }

        $d= implode(' ', $timeValues);
        dd($d);

Answer:

Try this, with carbon:

$seconds = 90060;
$dt = Carbon::now()->addSecond($seconds);
$dt_old = Carbon::now();
$days = $dt->diffInDays($dt_old);
$dt = $dt->subDays($days);
$hours = $dt->diffInHours($dt_old);
$dt = $dt->subHours($hours);
$minutes = $dt->diffInMinutes($dt_old);

echo $days.'<br>';
echo $hours.'<br>';
echo $minutes.'<br>';

Answer:

try this

$init = 150065;
$day = floor($init / 86400);
$hours = floor(($init -($day*86400)) / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;

echo "$day:$hours:$minutes:$seconds";