如何在php中将星期一或其他任何一天转换为一个月的所有未来日期?还要考虑存储在数据库中的假日。例如,考虑到今天的日期是2019年10月26日,2019年10月份的星期一应该产生一个日期,即2019年10日28日。但是,2019年11月的星期一应分别为2019年4月11日、2019年11日、2018年11月18日和25日。
下面的代码就是我能想到的。我已经使用了DateTime
的功能来读取和解析日期字符串。让我逐行解释。
$date = new DateTime("Saturday, November 2019");
$expected_month = $date->format('m');
$day = new DateTime(sprintf('First %s of %s %d', $date->format('l'), $date->format('F'), $date->format('Y')));
$now = new DateTime();
while($day->format('m') == $expected_month) {
if($day->getTimestamp() >= $now->getTimestamp()) {
print($day->format('d/m/Y'));
}
$day = $day->modify(sprintf("next %s", $date->format('l')));
echo "<br/>";
}
解释
PHP的[DateTime]
非常非常好地解析了这些日期字符串。例如:First Sunday of October 2019
、next Monday
、next week
、last Friday
等等。我在编码上述解决方案时使用了这种功能。
$date = DateTime("Monday, October 2019");
这是我们的输入。我们想找到2019年10月的所有星期一
$expected_month = $date->format('m');
我们将使用一个循环来限制自己只能打印所选月份的天数。为此,我们使用$expected_month
。$day = new DateTime(sprintf('First %s of %s %d', $date->format('l'), $date->format('F'), $date->format('Y')));
此行将当月第一个星期一的时间戳分配给$day
。
while
循环检查我们是否在当前月份。在它的主体中,我们使用next Monday
来获取十月的下一个星期一的日期,并将其分配给$day
更新-1
已更正函数以跳过过去的日期。
更新-2
根据@Dharman的建议,在阅读了DateTime
更受欢迎的的一些良好解释后,使用DateTime
而不是strtotime
更新-3更新代码以包含今天的日期。