此功能应该为您提供所需的内容:
function _get_granulation($granulation, $now = null) {
if (is_null($now)) $now = time();
$daySecs = date('G', $now) * 3600 + date('i', $now) * 60 + date('s', $now);
$segment = $granulation * floor($daySecs / $granulation);
$hrs = floor($segment / 3600);
$min = floor(($segment - $hrs * 3600) / 60);
$sec = $segment - $hrs * 3600 - $min * 60;
return date('H:i:s', mktime($hrs, $min, $sec));
}
我不直接使用 unix 时间戳来避免夏令时问题,而是使用实际的小时/分钟/秒值。
我添加了一个额外的参数来帮助测试,所以我们不必总是使用当前时间。这允许这样的测试脚本:
$times = array('10:30:00', '07:59:00', '23:20:00');
$granulations = array(21600, 14400, 3600, 1800);
foreach ($granulations as $g) foreach ($times as $t) {
$segment = _get_granulation($g, strtotime($t));
echo("{$t} / {$g} = {$segment}\n");
}
产生这样的输出:
10:30:00 / 21600 = 06:00:00
07:59:00 / 21600 = 06:00:00
23:20:00 / 21600 = 18:00:00
10:30:00 / 14400 = 08:00:00
07:59:00 / 14400 = 04:00:00
23:20:00 / 14400 = 20:00:00
10:30:00 / 3600 = 10:00:00
07:59:00 / 3600 = 07:00:00
23:20:00 / 3600 = 23:00:00
10:30:00 / 1800 = 10:30:00
07:59:00 / 1800 = 07:30:00
23:20:00 / 1800 = 23:00:00