How to round unix timestamp up and down to nearest half hour?

后端 未结 10 1934
名媛妹妹
名媛妹妹 2020-12-14 17:16

Ok so I am working on a calendar application within my CRM system and I need to find the upper and lower bounds of the half an hour surrorunding the timestamp at which someb

相关标签:
10条回答
  • 2020-12-14 17:46

    I'd use the localtime and the mktime function.

    $localtime = localtime($time, true);
    $localtime['tm_sec'] = 0;
    $localtime['tm_min'] = 30;
    $time = mktime($localtime);
    
    0 讨论(0)
  • 2020-12-14 17:50

    Far from my best work... but here's some functions for working with string or unix time stamp.

    /**
     * Takes a timestamp like "2016-10-01 17:59:01" and returns "2016-10-01 18:00"
     * Note: assumes timestamp is in UTC
     * 
     * @param $timestampString - a valid string which will be converted to unix with time()
     * @param int $mins - interval to round to (ex: 15, 30, 60);
     * @param string $format - the format to return the timestamp default is Y-m-d H:i
     * @return bool|string
     */
    function roundTimeString( $timestampString, $mins = 30, $format="Y-m-d H:i") {
        return gmdate( $format, roundTimeUnix( time($timestampString), $mins ));
    }
    
    /**
     * Rounds the time to the nearest minute interval, example: 15 would round times to 0, 15, 30,45
     * if $mins = 60, 1:00, 2:00
     * @param $unixTimestamp
     * @param int $mins
     * @return mixed
     */
    function roundTimeUnix( $unixTimestamp, $mins = 30 ) {
        $roundSecs = $mins*60;
        $offset = $unixTimestamp % $roundSecs;
        $prev = $unixTimestamp - $offset;
        if( $offset > $roundSecs/2 ) {
            return $prev + $roundSecs;
        }
        return $prev;
    }
    
    0 讨论(0)
  • 2020-12-14 17:54

    Use modulo.

    $prev = 1330518155 - (1330518155 % 1800);
    $next = $prev + 1800;
    

    The modulo operator gives the remainder part of division.

    0 讨论(0)
  • 2020-12-14 17:55

    Here's a more semantic method for those that have to make a few of these, perhaps at certain times of the day.

    $time = strtotime(date('Y-m-d H:00:00'));
    

    You can change that H to any 0-23 number, so you can round to that hour of that day.

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