制作使用PHP日期函数
问题描述:
事件的全年日程表我有具有以下性质的事件:制作使用PHP日期函数
id
name
weekday
所以,事件每星期发生在该工作日。我想创建一个包含所有日期的数组(格式:dd-mm-yyyy),当该事件将发生两个特定的日期。
我无法弄清楚适当的逻辑/代码。
我实现下面的代码:
$day = date('d');//returns today's date in 2-digit format.
$year = date('Y');//4-digit format of current year
$month = date('m');//2-digit format of current month
$cal = array();
$ttdayid = $weekday;//5
$tt = 0;
$tt = abs($day-$ttdayid);
$ttday = $date - $tt;
while ($ttday>0) {
if ($ttday<10) {
$ttday = '0' . $ttday;
}
$arr = array(
'id' => $id,
'title' => $name,
'start' => $year . '-' . $month . '-' . $ttday
);
array_push($cal, $arr);
$ttday-= 7;
}
上面的代码只有在今天之前的作品当月。我无法弄清楚如何扩展它以显示整年的前几个月和下一个月的日期。另外,如何将闰年纳入案例。
答
使用DateTime()
对象:
$current = new DateTime(); // creates a date for "today" by default
$end = new DateTime('yyyy-mm-dd'); // the ending date
$interval = new DateInterval('P7D'); // 1 week
while($current <= $end) {
$cal[] = $current->format('Y-m-d');
$current = $current->add($interval);
}
考虑使用['的DateTime()'](http://www.php.net/manual/en/book.datetime.php)。它使这样做更容易。 –