我试图选择星期五/星期六或者3日,18日,30日,31日......这是第一次。
真实示例:当前日期是2017年1月10日星期二。
选项:
我的代码应该选择2017年1月13日星期五。
PHP
$dayOfWeekArray = ['friday', 'saturday'];
$dayOfMonthArray = [3, 18, 30, 31];
foreach ($dayOfWeekArray as $dayOfWeek) {
$nextDayDate = new DateTime("next $dayOfWeek");
foreach ($dayOfMonthArray as $dayOfMonth) {
# Continue if $nextDayDate is before, or equals, whichever date $dayOfMonth turns out to be.
# Otherwise, determine which comes first, $nextDayDate or $dayOfMonth
}
}
问题:如何将$dayOfMonth
变成日期?
答案 0 :(得分:1)
我会使用DatePeriod
以1天为间隔循环几天,直到格式化日期与您要查找的值之一匹配 -
$start = new \DateTime("2017-01-10");
// You can probably do some math to determine the minimum number needed here
// php version 7.1.5
// $end = (clone $start)->modify("+31 days");
// php version 5.6
$end = clone $start;
$end->modify("+31 days");
$interval = new \DateInterval("P1D"); // An interval of 1 day
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $date) {
if (in_array($date->format('l'), ['Friday', 'Saturday']) || in_array((int) $date->format('d'), [3, 18, 30, 31])) {
break;
}
}
echo $date->format('l, Y-m-d') ;
// outputs 'Friday, 2017-01-13'
我想你要求的最后日期不是2017-01-13如果当天已经是2017-01-13 - 在这种情况下你可以在开始日加一天,比如{{1 }}
答案 1 :(得分:0)
假设您想知道当前月份和年份的dayOfMonth,您可以使用DateTime的createFromFormat
函数(http://php.net/manual/en/datetime.createfromformat.php),例如
$dayOfWeekArray = ['friday', 'saturday'];
$dayOfMonthArray = [3, 18, 30, 31];
$currentDate = new DateTime('now');
foreach ($dayOfWeekArray as $dayOfWeek) {
...
foreach ($dayOfMonthArray as $dayOfMonth) {
$nextDayOfMonthDateString = $dayOfMonth.'-'.$currentDate->format('m-Y');
$nextDayOfMonthDate = DateTime::createFromFormat('d-m-Y', $nextDayOfMonthDateString);
...
}
}