I would like to convert a variable $uptime
which is seconds, into days, hours, minutes and seconds.
Example:
A variation on @Glavić's answer - this one hides leading zeros for shorter results and uses plurals in correct places. It also removes unnecessary precision (e.g. if the time difference is over 2 hours, you probably don't care how many minutes or seconds).
function secondsToTime($seconds)
{
$dtF = new \DateTime('@0');
$dtT = new \DateTime("@$seconds");
$dateInterval = $dtF->diff($dtT);
$days_t = 'day';
$hours_t = 'hour';
$minutes_t = 'minute';
$seconds_t = 'second';
if ((int)$dateInterval->d > 1) {
$days_t = 'days';
}
if ((int)$dateInterval->h > 1) {
$hours_t = 'hours';
}
if ((int)$dateInterval->i > 1) {
$minutes_t = 'minutes';
}
if ((int)$dateInterval->s > 1) {
$seconds_t = 'seconds';
}
if ((int)$dateInterval->d > 0) {
if ((int)$dateInterval->d > 1 || (int)$dateInterval->h === 0) {
return $dateInterval->format("%a $days_t");
} else {
return $dateInterval->format("%a $days_t, %h $hours_t");
}
} else if ((int)$dateInterval->h > 0) {
if ((int)$dateInterval->h > 1 || (int)$dateInterval->i === 0) {
return $dateInterval->format("%h $hours_t");
} else {
return $dateInterval->format("%h $hours_t, %i $minutes_t");
}
} else if ((int)$dateInterval->i > 0) {
if ((int)$dateInterval->i > 1 || (int)$dateInterval->s === 0) {
return $dateInterval->format("%i $minutes_t");
} else {
return $dateInterval->format("%i $minutes_t, %s $seconds_t");
}
} else {
return $dateInterval->format("%s $seconds_t");
}
}
php > echo secondsToTime(60);
1 minute
php > echo secondsToTime(61);
1 minute, 1 second
php > echo secondsToTime(120);
2 minutes
php > echo secondsToTime(121);
2 minutes
php > echo secondsToTime(2000);
33 minutes
php > echo secondsToTime(4000);
1 hour, 6 minutes
php > echo secondsToTime(4001);
1 hour, 6 minutes
php > echo secondsToTime(40001);
11 hours
php > echo secondsToTime(400000);
4 days