PHP time intervals

亡梦爱人 提交于 2019-12-20 05:58:21

问题


I'm looking for a solution to something which seems like it should be pretty simple, but it doesn't seem that I can find any good answers on here, and I can't seem to get it to work myself.

What I'm looking for is to set a start time, an end time, and then iterate through a set of times between given a time interval. Say, for example, 9:00 AM - 5:00 PM are the start times, and the values returned between these times at half hour intervals are 9:30, 10:00, 10:30, 11:00, etc.

Here's some pseudo-code, because I'm not exactly sure what I need to plug in here (at least nothing I've tried has worked)...

for ($i = *start time*; $i = *end time*; $i += *time interval*) {
    echo $i;
}

Any ideas on this?


回答1:


Off of the top of my head. You can tweak as necessary.

$start    = new DateTime('2013-08-14 09:00:00');
$end      = new DateTime('2013-08-14 17:00:00');
$interval = new DateInterval('PT30M');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt)
{
    // do something
    echo $dt->format('H:iA');
}

Links

  • DateTime
  • DateInterval
  • DatePeriod


来源:https://stackoverflow.com/questions/18233794/php-time-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!