PHP round the time to the nearest 15 seconds

后端 未结 3 1755
遥遥无期
遥遥无期 2021-01-21 03:32

This is not a duplicate question, but involves a little understanding about time.

I need a solution to the following problem I have a number of specifically produced tim

相关标签:
3条回答
  • 2021-01-21 04:14

    Convert the date to seconds using strtotime and then just work in seconds.

    $seconds = strtotime($date);
    $seconds /= 15;
    $seconds = round($seconds);
    $seconds *= 15;
    $date = date("Y-m-d H:i:s", $seconds);
    
    0 讨论(0)
  • 2021-01-21 04:24
    $seconds = ($hr * 60 + $mn) * 60 + $sc; // convert to seconds
    $rounded = round($seconds/15)*15;       // round
    $sc = $rounded % 60;                    // get seconds
    $mn = ($rounded - $sc) / 60 % 60;       // get minutes
    $hr = ($rounded - $sc - $mn * 60) / 60; // get hours
    
    0 讨论(0)
  • 2021-01-21 04:26

    You're massively overcomplicating this, just do rounding on the Unix timestamp level:

    function roundMyTime($time)
    {
      $time = strtotime($time);
      $time = 15*round($time/15);
      echo date('H:i:s', $time)."\n";
    }
    roundMyTime('18:35:17');
    roundMyTime('18:35:27');
    roundMyTime('18:35:37');
    roundMyTime('18:35:47');
    roundMyTime('18:35:57');
    roundMyTime('18:36:07');
    roundMyTime('18:36:17');
    

    Outputs:

    18:35:15
    18:35:30
    18:35:30
    18:35:45
    18:36:00
    18:36:00
    18:36:15
    

    Demo here.

    0 讨论(0)
提交回复
热议问题