php - 间隔5分钟
问题描述
我正在尝试分隔日期,例如:
$arr=array(
"2018-06-27 20:30:20",
"2018-06-27 20:31:20",
"2018-06-27 20:37:20",
"2018-06-27 20:45:20",
"2018-06-27 20:48:20"
);
正如您所看到的,分钟之间的差异只有 1 分钟甚至几秒钟。
我想要完成的是强制日期为 5 分钟间隔。
示例输出
2018-06-27 20:30:00
2018-06-27 20:35:00
2018-06-27 20:40:00
2018-06-27 20:45:00
2018-06-27 20:50:00
这是我的代码
function roundToNearestMinuteInterval($time)
{
$time = (round(strtotime($time) / 300)) * 300;
return date('Y-m-d H:i:s', $time);
}
$temp="";
$wave=1;
foreach($arr as $a) {
if(empty($temp)) {
$temp= roundToNearestMinuteInterval($a);
}
$date= roundToNearestMinuteInterval($a);
if($temp==$date && $wave!=1){
$new=date('Y-m-d H:i:s',strtotime('+3 minutes',strtotime($a)));
$date= roundToNearestMinuteInterval($date);
$temp= $date;
}
$wave++;
echo $date."<br/>";
}
解决方案
如果您想要一个输出数组,其中包含输入数组中最早和最晚时间之间的所有 5 分钟(或其他间隔)时间,您可以在它们之间进行迭代,在每个循环中添加间隔:
$arr=array("2018-06-27 20:30:20","2018-06-27 20:31:20","2018-06-27 20:37:20","2018-06-27 20:45:20","2018-06-27 20:48:20");
function roundToNearestMinuteInterval($time, $interval) {
$timestamp = strtotime($time);
$rounded = round($timestamp / ($interval * 60), 0) * $interval * 60;
return $rounded;
}
$interval = 5; // minutes
$start = roundToNearestMinuteInterval(min($arr), $interval);
$end = roundToNearestMinuteInterval(max($arr), $interval);
for (; $start <= $end; $start += $interval * 60) {
$results[] = date('Y-m-d H:i:s', $start);
}
print_r($results);
输出:
Array
(
[0] => 2018-06-27 20:30:00
[1] => 2018-06-27 20:35:00
[2] => 2018-06-27 20:40:00
[3] => 2018-06-27 20:45:00
[4] => 2018-06-27 20:50:00
)
推荐阅读
- excel - 查看单元格中的数字 (x) 并复制行 (x) 次
- azure-ad-b2c - MSAL.js 2.0 注册用户流程
- android - kotlinx 协程测试。liveData {...} 中的 withContext {...} 完成后不会切换回之前的上下文
- javascript - res.end 不停止脚本执行
- angular - ngx-bootstrap bsValueChange 被重复调用
- c# - InvalidOperationException 的未知原因?
- javascript - 为什么在播放音频文件之前不加载 HTML 链接
- reactjs - 有人可以帮我创建反应应用程序吗?创建反应应用程序时的问题
- react-native - 如何在 react-native-maps 中覆盖选定的自定义标记
- python - 如何将计数数据帧转换为概率密度函数