这是一个将四舍五入(向上、向下或只是简单地四舍五入)到任意数量的秒、分钟或小时的函数。灵感来自@esqilin 's answer
许多博萨人为了给你带来这些信息而死。
PHP 7,虽然可能不难调整到 5。
/**
* Round $datetime to nearest <$precision> <$unit>s - e.g nearest 10 seconds -- or always up/down per $calc
* @param \DateTimeInterface $datetime
* @param int $precision Round to the nearest number of {$unit}s
* @param string $unit 'h', 'm', or 's' for Hours, Minutes, or Seconds; or PHP's 'G'/'H' (hours) or 'i' (minutes)
* @param int $calc -1, 0, or 1 = floor, round, or ceiling calculations
* @return \DateTimeInterface
* @throws \Exception
*/
function roundTime( \DateTimeInterface $datetime, int $precision = 1, string $unit = 's', int $calc = 0 ) :\DateTimeInterface {
$offset = $datetime->format( 'Z' );
$datetime = ( clone $datetime )->modify( "+$offset seconds" );
switch( $unit ) { // convert human readable units to PHP DateTime format string
case 'h':
case 'H':
$unit = 'G';
break;
case 'm':
$unit = 'i';
break;
// 's' -> 's', no change
}
$secs = [ 'G'=>3600, 'i'=>60, 's'=>1 ]; // seconds per hour/minute/second
if( ! in_array( $unit, array_keys( $secs ) ) ) {
trigger_error( "Unknown \$unit parameter '$unit' in " . __FUNCTION__ . ". Recognized formats are 'h', 'm', 's', (hours/minutes/seconds), or PHP's 'G', 'H', or 'i'" );
return $datetime;
}
$precision = $precision * $secs[$unit];
if( -1 === $calc ) {
$round = 0;
} elseif( 1 === $calc ) {
$round = $precision;
} elseif( 1 == $precision && 's' == $unit ) { // in this -- and only this -- case, we need partial seconds
$round = ( (int) $datetime->format('v') ) >= 500 ? 1 : 0;
} else {
$round = ( ( (int) $datetime->format('U') ) % $precision >= ( $precision/2 ) ) ? $precision : 0;
}
$result = $datetime->setTimestamp( ( $precision * floor( $datetime->format('U') / $precision ) ) + $round - $offset );
return $result;
}
在问题中提出的情况下,您将使用:
$datetime = new DateTime($mysqldata);
echo roundTime( $datetime, 10, 'm', 1 );