开始和结束时间,分为 1 小时段
我有一个 timestamp
格式的开始和结束时间。我想将它们分成几个时间段,例如 1 小时。
$t1 = strtotime('2010-05-06 12:00:00');
$t2 = strtotime('2010-05-06 18:00:00');
$timeslots = array();
while ($t1 < $t2) {
$t1 = $t1 + 3600;
$timeslots[] = $t1;
}
foreach ( $timeslots as $slot ) {
echo date("Y-m-d H:i:s", $slot) . '<br/>';
}
这是最有效的方法还是有更好、更通用的方法?
有时,当尝试使用不同长度时隙的其他数字时,会出现致命错误:允许的内存大小耗尽,这让我认为它不是很有效。虽然现在似乎没有发生这种情况......
(我正在构建一个预订系统)
I have a start and end time in a timestamp
format. I want to split these into timeslots of e.g 1 hour.
$t1 = strtotime('2010-05-06 12:00:00');
$t2 = strtotime('2010-05-06 18:00:00');
$timeslots = array();
while ($t1 < $t2) {
$t1 = $t1 + 3600;
$timeslots[] = $t1;
}
foreach ( $timeslots as $slot ) {
echo date("Y-m-d H:i:s", $slot) . '<br/>';
}
Is this the most efficient way to do it or is there a better, more versatile way to do this?
Occasionally when trying it with other numbers for different length timeslots there was a Fatal error: Allowed memory size exhausted which makes me think it's not very efficient. Though that doesn't appear to be happening now...
(I'm building a booking sytem)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过
有点相同但更干净。正如所说,strtotime 将处理日期变化,例如闰年。您的 PHP 内存限制设置为多少?可能太低了。
Have you tried
Somewhat the same but cleaner. And as was said strtotime will handle date changes like leap years. What is your PHP memory limit set at? Might be too low.
使用 PHP 5.3
using php 5.3
而不是
You'll be better off with
后者会调整夏令时、闰年等。
否则,您的代码看起来不错。如果内存不足,可能是由于无限循环。您可能需要添加代码以确保 $t2 大于 $t1,如果不是则切换它们。
Rather than
You'll be better off with
The latter will adjust to daylight savings time, leap years, etc.
Otherwise, your code looks fine. If you ran out of memory it was probably due to an infinite loop. You probably want to add code to make sure that $t2 is larger than $t1, and to switch them if they aren't.