PHP Function to Convert Seconds into Years, Months, Days, Hours, Minutes and Seconds.

844

In this post I am going to share quick PHP Function to Convert Seconds into Years, Months, Days, Hours, Minutes and Seconds. It’ll convert total number of seconds into human readable format Years, Months, Days, Hours, Minutes and Seconds (eg: 246395678 seconds = 7 Years, 9 months, 21 days, 19 hours, 14 minutes and 38 seconds). After PHP 5.3 release you don’t need to manually convert seconds into other readable format. There is a predefined function in php called date_diff to convert seconds into Years, Months, Days, Hours, Minutes and Seconds.

Just copy and paste below function in your PHP page.

<?php
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'); 
  }
?>

After that call convertSecToTime($sec) and pass total number of seconds which need to convert into Years, Months, Days, Hours, Minutes and Seconds.

echo convertSecToTime(246395678);
//OUTPUT: 7 Years, 9 months, 21 days, 19 hours, 14 minutes and 38 seconds