Intel Fierce
Intel Fierce

Reputation: 11

PHP Function To Convert Seconds Into Years, Months, Days, Hours, Minutes And Seconds

I don't reall have much knowledge about this but I needed a function that converted secs into y,m,d,h

function convertSecToTime($sec) 
 {
  $date1 = new DateTime("@0");
  $date2 = new DateTime("@$sec");
  $interval =  date_diff($date1, $date2);
  return $interval->format('%y Years, %m months, %d days, %h hours, %i minutes and %s seconds');
  // convert into Days, Hours, Minutes
  // return $interval->format('%a days, %h hours, %i minutes and %s seconds'); 
  }

print_r(convertSecToTime(500));

the output it would give would be

0 Years, 0 months, 0 days, 0 hours, 8 minutes and 20 seconds

can someone help me modify this function so it don't show all the 0 values and only showed 8mins and 20 sec

Upvotes: 1

Views: 1195

Answers (1)

Phiter
Phiter

Reputation: 14992

I understand that you wish to show only the values that aren't zero.

This will require a bit of work. You need to get the individual values from the interval and see if they are zero, and get only the ones that aren't.

You can put those values on an array and join them, but you need to know what each value represents, so you need some form of label (years, months, etc).

You'll also need to remove the s from the label if the value is 1, so that's simple: you just need to check if the value is 1 and take the substring of the label without the last character (substr($str, 0, -1)).

Then you could just join those values with a comma, but you won't have the "and" part in the last index, so you have to check if there is more than one item in your array and join the last one with an "and" string.

This is the final result:

<?php

function convertSecToTime($sec)
{
    $date1 = new DateTime("@0");
    $date2 = new DateTime("@$sec");
    $interval = date_diff($date1, $date2);
    $parts = ['years' => 'y', 'months' => 'm', 'days' => 'd', 'hours' => 'h', 'minutes' => 'i', 'seconds' => 's'];
    $formatted = [];
    foreach($parts as $i => $part)
    {
        $value = $interval->$part;
        if ($value !== 0)
        {
            if ($value == 1){
                $i = substr($i, 0, -1);
            }
            $formatted[] = "$value $i";
        }
    }

    if (count($formatted) == 1)
    {
        return $formatted[0];
    }
    else
    {
        $str = implode(', ', array_slice($formatted, 0, -1));
        $str.= ' and ' . $formatted[count($formatted) - 1];
        return $str;
    }
}

echo convertSecToTime(500); //8 minutes and 20 seconds
echo convertSecToTime(1500); //25 minutes
echo convertSecToTime(2500); //41 minutes and 40 seconds
echo convertSecToTime(3500); //58 minutes and 20 seconds
echo convertSecToTime(4500); //1 hour and 15 minutes
echo convertSecToTime(5500); //1 hour, 31 minutes and 40 seconds

Upvotes: 4

Related Questions