How to convert number of seconds to plain English string with larger units as needed?

Viewed 188

My Timestamp To String Function

// Timestamp To String
function time2string($time) {

    // DAYS
    $d = floor($time/86400);
    if ($d > 0) { $_d = $d.($d > 1 ? ' days' : ' day'); }
    else { $_d = ""; }

    // HOURS
    $h = floor(($time-$d*86400)/3600);
    if ($h > 0) { $_h = $h.($h > 1 ? ' hours' : ' hour'); }
    else { $_h = ""; }

    // MINUTES
    $m = floor(($time-($d*86400+$h*3600))/60);
    if ($m > 0) { $_m = $m.($m > 1 ? ' minutes' : ' minute'); }
    else { $_m = ""; }

    // SECONDS
    $s = $time-($d*86400+$h*3600+$m*60);
    if ($s >0) { $_s = $s.($s > 1 ? ' seconds' : ' second'); }
    else { $s = ""; }

    $time_str = $_d.' '.$_h.' '.$_m.' '.$_s;
    return $time_str;
}

Live Demo: https://eval.in/826278

Usage

time2string(22500)

6 hours 15 minutes

Desired Output

  • 1 second
  • 1 minute and 1 second
  • 1 hour, 1 minute and 1 second
  • 1 day, 1 hour, 1 minute and 1 second
2 Answers
Related