次のようなものが必要です。
$date0 = \DateTime::createFromFormat('M j, Y', 'Oct 1, 2013');
$date1 = \DateTime::createFromFormat('M j, Y', 'Oct 10, 2013');
$day = new \DateInterval('P1D');
while ($date0 <= $date1) {
echo $date0->format('M j, Y'), PHP_EOL;
$date0->add($day);
}
出力:
Oct 1, 2013
Oct 2, 2013
Oct 3, 2013
Oct 4, 2013
Oct 5, 2013
Oct 6, 2013
Oct 7, 2013
Oct 8, 2013
Oct 9, 2013
Oct 10, 2013
while
目的の動作を得るために、ループ内にさらにチェックを追加できます。
// These could come from the database
$dates = ['Oct 4, 2013', 'Oct 7, 2013', 'Oct 8, 2013'];
$fromDate = 'Oct 1, 2013';
$toDate = 'Oct 10, 2013';
// Solution
// Remove comments below in order to always show the start and end dates
//$dates[] = $fromDate;
//$dates[] = $toDate;
$date0 = \DateTime::createFromFormat('M j, Y', $fromDate);
$date1 = \DateTime::createFromFormat('M j, Y', $toDate);
$day = new \DateInterval('P1D');
while ($date0 <= $date1) {
$string = $date0->format('M j, Y');
echo (in_array($string, $dates) ? $string : 'Absent'), PHP_EOL;
$date0->add($day);
}
出力:
Absent
Absent
Absent
Oct 4, 2013
Absent
Absent
Oct 7, 2013
Oct 8, 2013
Absent
Absent
PHP < 5.3 の編集
基本的な例:
$date0 = new DateTime('Oct 1, 2013');
$date1 = new DateTime('Oct 10, 2013');
while ($date0 <= $date1) {
echo $date0->format('M j, Y'), PHP_EOL;
$date0->modify('+1 day');
}
高度な例:
// These could come from the database
$dates = ['Oct 4, 2013', 'Oct 7, 2013', 'Oct 8, 2013'];
$fromDate = 'Oct 1, 2013';
$toDate = 'Oct 10, 2013';
// Solution
// Remove comments below in order to always show the start and end dates
//$dates[] = $fromDate;
//$dates[] = $toDate;
$date0 = new DateTime($fromDate);
$date1 = new DateTime($toDate);
while ($date0 <= $date1) {
$string = $date0->format('M j, Y');
echo (in_array($string, $dates) ? $string : 'Absent'), PHP_EOL;
$date0->modify('+1 day');
}