以下代码 sn-p 将生成一个数组 $oddDays,其中将包含所选月份中的所有奇数天。
function getDateList($year, $month, $type = 'odd')
{
$now = new DateTime();
if (!$year) {
$year = $now->format('Y');
}
if (!$month) {
$month = $now->format('m');
}
// Let's start with the month you want the days from
$startDate = DateTime::createFromFormat('Y-m-d', $year.'-'.$month.'-01');
// Get the end date based on the start date
$endDate = DateTime::createFromFormat('Y-m-d', $startDate->format('Y-m-t'));
// The interval to increase with
$interval = new DateInterval('P1D');
// Define our date period
$datePeriod = new DatePeriod($startDate, $interval, $endDate);
// Define array and loop through dates
$days = array();
foreach ($datePeriod as $key => $date) {
if ($type == 'odd') {
if ($key % 2 == 0) {
$days[] = $date->format('l d, ').strtoupper($date->format('M')).' '.$date->format('Y');
}
} elseif ($type == 'even') {
if ($key % 2 != 0) {
$days[] = $date->format('l d, ').strtoupper($date->format('M')).' '.$date->format('Y');
}
}
}
return $days;
}
echo "<pre>";
// Odd days
var_dump(getDateList('2018', '03', 'odd'));
// Even days
var_dump(getDateList('2018', '03', 'even'));
echo "</pre>";
输出
array(15) {
[0]=>
string(22) "Wednesday 01, AUG 2018"
[1]=>
string(19) "Friday 03, AUG 2018"
[2]=>
string(19) "Sunday 05, AUG 2018"
[3]=>
string(20) "Tuesday 07, AUG 2018"
[4]=>
string(21) "Thursday 09, AUG 2018"
[5]=>
string(21) "Saturday 11, AUG 2018"
[6]=>
string(19) "Monday 13, AUG 2018"
[7]=>
string(22) "Wednesday 15, AUG 2018"
[8]=>
string(19) "Friday 17, AUG 2018"
[9]=>
string(19) "Sunday 19, AUG 2018"
[10]=>
string(20) "Tuesday 21, AUG 2018"
[11]=>
string(21) "Thursday 23, AUG 2018"
[12]=>
string(21) "Saturday 25, AUG 2018"
[13]=>
string(19) "Monday 27, AUG 2018"
[14]=>
string(22) "Wednesday 29, AUG 2018"
}