我正试图返回下个月的第一个工作日,该日期应排除公共假日-我决定依靠strototime()
,因为这可以帮助您遍历日期。现在出现的问题是strototime()
可以返回“下个月的第一天”,但在“下个月的第二天等”时失败。有没有其他方法可以返回日期,还是应该以编程方式将这些日期放在一起?
这是我的剧本:
function getDODate() {
// Dates to select:
$dates = [
"first day of next month",
"second day of next month",
"third day of next month",
"forth day of next month",
"fifth day of next month",
"sixth day of next month",
"seventh day of next month"
];
// public holidays:
$publicHolidays = ['0101', '0501'];
foreach ($dates AS $day) {
// Get the dates for check:
$monthDay = date("md", strtotime($day));
$dayName = date("l", strtotime($day));
echo $monthDay."<br />";
// First, let's get the date to ensure it's not a public holiday:
if (!in_array($monthDay, $publicHolidays)) {
// Date does not fall on a public holiday, is it a weekend?
if (!in_array($dayName, ['Saturday', 'Sunday'])) {
// We've got a date that will work, return:
return date("Ymd", strtotime($day));
}
}
}
}
答案 0 :(得分:1)
您需要检查多次,因为将日期从周末增加到工作日可能会在公共假期降落。如果整周都是公众假期,而下一个约会又回到周末,该怎么办?
如果是周末,请查找下一个星期一。如果是公众假期,请跳至第二天。继续检查两者,直到两者都有效,然后完成。
$date = new DateTime("first day of next month");
$publicHolidays = ['01-01', '05-01']; // Format: mm-dd
while (true) {
// format("N") >= 6 == Weekend
if ($date->format("N") >= 6) {
// If Saturday or Sunday, add 1 or 2 days.
// N=6 (Saturday), 8-6 = 2, get monday
// N=7 (Sunday), 8-7 = 1, get monday
$date->modify("+".(8-$date->format("N"))." days");
} elseif (in_array($date->format("m-d"), $publicHolidays)) {
// This day is a public holiday! Add one.
$date->modify("+1 day");
} else {
break;
}
}
echo $date->format("Y-m-d");
答案 1 :(得分:-1)
漂亮吗?否。可以吗?你打赌!
function getDODate() {
// public holidays:
$publicHolidays = ['0101', '0501'];
// Iterate from the 1st - 7th for dates:
for($i=1;$i<=7;$i++) {
// Day of the month:
$day = "0".$i;
// Next Actual month:
$month = date("m",strtotime("next month"));
// DayMonth to compare for public holidays:
$monthDay = $month.$day;
// Fulldate (this will be returned:
$fullDate = date("Y").$monthDay;
// Day Name of the fullDate about:
$dayName = date("l", strtotime($fullDate));
// First, let's get the date to ensure it's not a public holiday:
if (!in_array($monthDay, $publicHolidays)) {
// Date does not fall on a public holiday, is it a weekend?
if (!in_array($dayName, ['Saturday', 'Sunday'])) {
// We've got a date that will work, return:
return $fullDate;
}
}
}
}