Welcome Guest, Not a member yet? Register   Sign In
how do you round current time to nearest 15 minutes [Solved]
#1

[eluser]Otemu[/eluser]
Not exactly a CodeIgniter question but native php but does anyone know how you round current time to nearest 15 minutes

I have some simple code displaying current time:
Code:
echo date('G:i');

Tried some formulas but haven't had much luck so far
example 18:27
should display 18:30

Cheers if anyone can help
#2

[eluser]InsiteFX[/eluser]
Found this not sure if it will help.
Code:
$signintime = '4:32 pm';
define( 'SIGN_IN', $signintime);
function minutes_round ($hour = SIGN_IN, $minutes = 5, $format = "H:i")
{
    $seconds = strtotime($hour);
    $rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
    return date($format, $rounded);
}

// use example:
// echo minutes_round(); // returns 16:30
#3

[eluser]timmahoney[/eluser]
I've used this before.

$minute = date("i");
$multiplier = round($minute / 15);
echo $multiplier * 15;
#4

[eluser]CroNiX[/eluser]
Code:
function round_minutes($minutes, $precision = 15)
{
  return round($minutes / $precision) * $precision;
}

Code:
echo round_minutes(date('i'));
#5

[eluser]Otemu[/eluser]
Great help guys, used timmahoney method in end(edit now using InsiteFX method), added switch so 17:59 will now go to 18:00.

Code:
$minute = date("i");
$nQuarter = round($minute / 15)* 15;
switch($nQuarter) {
    case 60:
$ntime = date('G', strtotime(" +1 hours"));
echo $ntime.':00';
        break;
    case 0:
    echo date('G').':00';
        break;
    default:
    echo date('G').':'.$nQuarter;

}

Actually looking at InsiteFX method probably works better as no need for switch

Final Code:

Code:
$ctime = date('G:i');
$minutes = 15;
$format = "G:i";
$seconds = strtotime($ctime);
$rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
echo date($format, $rounded);




Theme © iAndrew 2016 - Forum software by © MyBB