Matei Zoc
Matei Zoc

Reputation: 3919

Time() By 5 Minutes Select

PHP Function to convert time() seconds to time format Hour:Minutes

function secondsToTime($seconds) {
 $dtF = new \DateTime('@0');
 $dtT = new \DateTime("@$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
 return $dtF->diff($dtT)->format('%h:%i');
}

echo secondsToTime(time());

I need a function for something like:

If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50

But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...

Upvotes: 0

Views: 91

Answers (1)

John Conde
John Conde

Reputation: 219814

You need to round the minutes and then reformat your output date.

There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.

Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.

function secondsToTime() {
    $now      = new \DateTime();
    $cminutes = $now->format('i');
    $hour     = $now->format('H');
    $nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
    if ($nminutes > $cminutes) {
        $nminutes -= 5;
    }
    if ($nminutes === 60) {
        $nminutes = 0;
        $hour++;
    }
    if ($hour === 24) {
        $hour = 0;
    }
    return sprintf('%02d:%02d', $hour, $nminutes);
}

echo secondsToTime();

Demo

Upvotes: 2

Related Questions