I would like to convert a variable $uptime
which is seconds, into days, hours, minutes and seconds.
Example:
Based on the answer by Julian Moreno, but changed to give the response as a string (not an array), only include the time intervals required and not assume the plural.
The difference between this and the highest voted answer is:
For 259264
seconds, this code would give
3 days, 1 minute, 4 seconds
For 259264
seconds, the highest voted answer (by Glavić) would give
3 days, 0 hours, 1 minutes and 4 seconds
function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// Extract days
$days = floor($inputSeconds / $secondsInADay);
// Extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// Extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// Extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// Format and return
$timeParts = [];
$sections = [
'day' => (int)$days,
'hour' => (int)$hours,
'minute' => (int)$minutes,
'second' => (int)$seconds,
];
foreach ($sections as $name => $value){
if ($value > 0){
$timeParts[] = $value. ' '.$name.($value == 1 ? '' : 's');
}
}
return implode(', ', $timeParts);
}
I hope this helps someone.
function convert($seconds){
$string = "";
$days = intval(intval($seconds) / (3600*24));
$hours = (intval($seconds) / 3600) % 24;
$minutes = (intval($seconds) / 60) % 60;
$seconds = (intval($seconds)) % 60;
if($days> 0){
$string .= "$days days ";
}
if($hours > 0){
$string .= "$hours hours ";
}
if($minutes > 0){
$string .= "$minutes minutes ";
}
if ($seconds > 0){
$string .= "$seconds seconds";
}
return $string;
}
echo convert(3744000);
Here's some code that I like to use for the purpose of getting the duration between two dates. It accepts two dates and gives you a nice sentence structured reply.
This is a slightly modified version of the code found here.
<?php
function dateDiff($time1, $time2, $precision = 6, $offset = false) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
if (!$offset) {
$time2 = strtotime($time2);
}
else {
$time2 = strtotime($time2) - $offset;
}
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array(
'year',
'month',
'day',
'hour',
'minute',
'second'
);
$diffs = array();
// Loop thru all intervals
foreach($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval.= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
if (!empty($times)) {
// Return string with times
return implode(", ", $times);
}
else {
// Return 0 Seconds
}
return '0 Seconds';
}
Source: https://gist.github.com/ozh/8169202
This is a function i used in the past for substracting a date from another one related with your question, my principe was to get how many days, hours minutes and seconds has left until a product has expired :
$expirationDate = strtotime("2015-01-12 20:08:23");
$toDay = strtotime(date('Y-m-d H:i:s'));
$difference = abs($toDay - $expirationDate);
$days = floor($difference / 86400);
$hours = floor(($difference - $days * 86400) / 3600);
$minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
$seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);
echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";
Here it is a simple 8-lines PHP function that converts a number of seconds into a human readable string including number of months for large amounts of seconds:
PHP function seconds2human()
function seconds2human($ss) {
$s = $ss%60;
$m = floor(($ss%3600)/60);
$h = floor(($ss%86400)/3600);
$d = floor(($ss%2592000)/86400);
$M = floor($ss/2592000);
return "$M months, $d days, $h hours, $m minutes, $s seconds";
}
There are some very good answers here but none of them covered my needs. I built on Glavic's answer to add some extra features that I needed;
You can see a running version of the code here.
function secondsToHumanReadable(int $seconds, int $requiredParts = null)
{
$from = new \DateTime('@0');
$to = new \DateTime("@$seconds");
$interval = $from->diff($to);
$str = '';
$parts = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$includedParts = 0;
foreach ($parts as $key => $text) {
if ($requiredParts && $includedParts >= $requiredParts) {
break;
}
$currentPart = $interval->{$key};
if (empty($currentPart)) {
continue;
}
if (!empty($str)) {
$str .= ', ';
}
$str .= sprintf('%d %s', $currentPart, $text);
if ($currentPart > 1) {
// handle plural
$str .= 's';
}
$includedParts++;
}
return $str;
}