skip to Main Content

Basically i need if it’s more than or equal to 45 minutes, it must be rounded up. if it’s less than that, it must be rounded down

Example :

- 18:12 needs to be 18:00
- 18:32 needs to be 18:00
- 18:45 needs to be 19:00
- 18:52 needs to be 19:00
- etc.

I’m not sure if that’s possible. really need your help, thanks

3

Answers


  1. The best solution is probably using the Date function PHP has.

    if((int)date('i', strtotime('18:46')) >= 45){
        echo date('H:00', strtotime('+ 1 hour', strtotime('18:46')));
    } else {
        echo '18:46';
    }
    

    Also could be achieved with string functions but then you’ll need to account for midnight notations.

    An explode approach could start with:

    list($hours, $minutes) = explode(':', '18:46');
    

    A regex approach could start with:

    (?:[01]d|2[0-3]):(4[5-9]|5d)
    
    Login or Signup to reply.
  2. you can use function like this for 30 minutes

    function roundToHalfHour($timestring) {
        $minutes = date('i', strtotime($timestring));
        return $minutes - ($minutes % 30);
    }
    
    Login or Signup to reply.
  3. Solution with DateTime. Add 15 minutes and set minutes and seconds to 0.

      $date = '18:12';
      $dt = date_create($date)->modify('+15 Minutes');
      $dt->setTime($dt->format('H'),0,0,0);
    

    As a complete test https://3v4l.org/mXBaU

    $dateArr = ["18:12","18:44","18:45","18:59","19:01"];
    foreach($dateArr as $date){
      $dt = date_create($date)->modify('+15 Minutes');
      $dt->setTime($dt->format('H'),0,0,0);
    
      echo $date.' => '.$dt->format('H:i')."n";
    }
    

    Output:

    18:12 => 18:00
    18:44 => 18:00
    18:45 => 19:00
    18:59 => 19:00
    19:01 => 19:00
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search