PHP 5.3 DateTime用于重复发生的事件
我有一个日历应用程序,它使用较新的
PHP DateTime类.我有办法处理反复发生的事件,但看起来很糟糕,我想看看你们是否有更好的想法:
>我有一个定期活动,从2009年11月16日开始(2009年11月16日) 假设用户查看截止日期为3100的日历 – 此事件应该显示正常情况下每3天重复一次.问题是 – 如何计算该月的那些日子? ========================================= 这就是我基本上这样做的方式,但我知道我更容易丢失一些东西: >我计算存储为$daysDiff的月份开始(2009年12月1日)和事件开始日期(2009年11月16日)之间的天数差异 我的主要问题来自第1步.PHP DateInterval :: date_diff函数不计算天数差异.它会给我几年,几个月和几天.然后,我必须捏造这些数字以获得大约在3100年12月左右的估计日期. 当你像9999年一样走向未来时,这个估计可能会在一个月内消失,然后我必须减去很多3天的间隔才能到达我需要的地方. 解决方法
您可以将日期格式化为unix时间戳,然后使用模块化分区查找所选月份中的第一个实例,然后从那里开始增加3天.所以对于你的例子:
$startDate = new DateTime(20091116); $startTimestamp = $startDate->format('u'); $recursEvery = 259200; // 60*60*24*3 = seconds in 3 days // find the first occurrence in the selected month (September) $calendarDate = new DateTime(31000901); // init to Sept 1,3100 while (0 != (($calendarDate->format('u') - $startTimestamp) % $recursEvery)) { $calendarDate->modify('+1 day'); } $effectiveDates = array(); while ($calendarDate->format('m') == 9) { $effectiveDates[] = clone $calendarDate; $calendarDate->modify('+3 day'); } //$effectiveDates is an array of every date the event occurs in September,3100. 显然,你有一些变量可以换出,所以用户可以选择任何一个月,但这应该是基本的算法.另外,确保您的DateTimes是正确的日期,但时间设置为00:00:00,否则第一个while循环将永远不会解析.这也假设您确保所选日期晚于事件的开始日期. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |