Round minute down to nearest quarter hour

Round minute down to nearest quarter hour

Asked on January 2, 2019 in PHP.
Add Comment


  • 3 Answer(s)

    This code is enough for get the solution,

    function roundToQuarterHour($timestring) {
        $minutes = date('i', strtotime($timestring));
        return $minutes - ($minutes % 15);
    }
    
    Answered on January 2, 2019.
    Add Comment

    The solution is very simple,

    $seconds = time();
    $rounded_seconds = round($seconds / (15 * 60)) * (15 * 60);
     
    echo "Original: " . date('H:i', $seconds) . "\n";
    echo "Rounded: " . date('H:i', $rounded_seconds) . "\n";
    

    The code above can be used for both original and rounded value.

    We can also use floor() function instead of round() which is used for round it down.

    Answered on January 2, 2019.
    Add Comment

    Try to use this code,

    $now = getdate();
    $minutes = $now['minutes'] - $now['minutes']%15;
     
      //Can add this to go to the nearest 15min interval (up or down)
      $rmin = $now['minutes']%15;
      if ($rmin > 7){
        $minutes = $now['minutes'] + (15-$rmin);
      }else{
          $minutes = $now['minutes'] - $rmin;
      }
     
    $rounded = $now['hours'].":".$minutes;
    echo $rounded;
    
    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.