1

I want to display a number of hours in days and hours as a human readable string but I need that 1 day be equal to 7 hours, so a working day.

I found this solution, but based on 1 day equal to 24 hours :

function secondsToTime($seconds) {
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$seconds");
    return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}

source: Convert seconds into days, hours, minutes and seconds

Community
  • 1
  • 1
abenevaut
  • 768
  • 1
  • 9
  • 23
  • 3
    DateTime won't help you as it assumes the day is between 23 and 25 hours long. You probably need to do your own thing. – apokryfos Sep 05 '16 at 13:36

2 Answers2

4

DateTime won't help here. You need to count it on your own.

But this is simple math. Integer division for days and modulo for hours.

$hours = 12345;

$days = floor($hours/7);
$restHours = $hours%7;

echo "{$days} days, {$restHours} hours"; //1763 days, 4 hours
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
  • Also basic match to get from seconds to hours. – Jonnix Sep 05 '16 at 13:42
  • 1
    @JonStirling yes, but OP wrote `display a number of hours in days and hours`, so I assumed hours are input data although his funciton probably takes time in seconds as argument. – Jakub Matczak Sep 05 '16 at 13:44
  • 1
    Thank you, I imagine that it was a problem of math but I could not do this simple calculation. I always forgot the use of modulo. – abenevaut Sep 06 '16 at 07:02
2

Custom made code to deal with this (probably on of 1000 ways on can implement this, I don't claim this to be the best, or good or anything like that).

function secondsToTime($seconds) {
        $totalMinutes = intval($seconds / 60);
        $totalHours = intval($totalMinutes / 60);
        $totalDays = intval($totalHours / 7);
        echo "$totalDays days and ".($totalHours%7)." hours ".($totalMinutes%60)." minutes and ".($seconds%60)." seconds";             
}

e.g.

secondsToTime(8*60*60);

prints

1 days and 1 hours 0 minutes and 0 seconds

apokryfos
  • 38,771
  • 9
  • 70
  • 114