开始和结束时间,分为 1 小时段

发布于 2024-08-26 09:26:06 字数 481 浏览 5 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

删除→记忆 2024-09-02 09:26:06

您是否尝试过

while ($t1 < $t2) {
   $t1 = strtotime('+1 hour', $t1);
   $timeslots[] = date('Y-m-d H:i:s', $t1);
}

foreach ( $timeslots as $slot ) {
   echo $slot . '<br/>';
}

有点相同但更干净。正如所说,strtotime 将处理日期变化,例如闰年。您的 PHP 内存限制设置为多少?可能太低了。

Have you tried

while ($t1 < $t2) {
   $t1 = strtotime('+1 hour', $t1);
   $timeslots[] = date('Y-m-d H:i:s', $t1);
}

foreach ( $timeslots as $slot ) {
   echo $slot . '<br/>';
}

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.

恍梦境° 2024-09-02 09:26:06

使用 PHP 5.3

$dateTimes = new DatePeriod(
    new DateTime($start),
    new DateInterval('PT1H'),
    new DateTime($end)
);

foreach ($dateTimes as $dt) {
    echo $dt->format('Y-m-d H:i:s'), "\n";
}

using php 5.3

$dateTimes = new DatePeriod(
    new DateTime($start),
    new DateInterval('PT1H'),
    new DateTime($end)
);

foreach ($dateTimes as $dt) {
    echo $dt->format('Y-m-d H:i:s'), "\n";
}
呆橘 2024-09-02 09:26:06

而不是

$t1 = $t1 + 3600;

You'll be better off with

$t1 = strtotime('+1 hour', $t1);

后者会调整夏令时、闰年等。

否则,您的代码看起来不错。如果内存不足,可能是由于无限循环。您可能需要添加代码以确保 $t2 大于 $t1,如果不是则切换它们。

Rather than

$t1 = $t1 + 3600;

You'll be better off with

$t1 = strtotime('+1 hour', $t1);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文