[英]Get Weekend Dates in php
我正在开发一个 php 应用程序,它要求我提取两个日期之间的周末日期,然后将它们作为单个记录插入到 mysql 数据库中。
我在想是否有更简单的方法,而不是在开始日期和结束日期之间进行循环,并为每个日期检查date('l', strtotime($date))
返回“Saturday”或“Sunday” ”
谢谢你的时间
苏尼尔
如果您使用的是较旧的 PHP 安装(或没有 DateTime 类):
$now = strtotime("now");
$end_date = strtotime("+3 weeks");
while (date("Y-m-d", $now) != date("Y-m-d", $end_date)) {
$day_index = date("w", $now);
if ($day_index == 0 || $day_index == 6) {
// Print or store the weekends here
}
$now = strtotime(date("Y-m-d", $now) . "+1 day");
}
我们遍历日期范围并检查这一天是0
还是6
索引(星期日或星期六)。
好吧,php Date("N") 为您提供了一周中的哪一天,其中 1 是星期一,7 是星期日,因此您可以很容易地将其实现到 if 语句中。
$now = new DateTime("now");
$now->setTime(0,0);
if (($now->format("l") == "Saturday") || ($now->format("l") == "Sunday"))
$d = $now;
else
$d = new DateTime("next saturday");
$oneday = new DateInterval("P1D");
$sixdays = new DateInterval("P6D");
$res = array();
while ($d->getTimestamp() <= $endTimestamp) {
$res[] = $d->format("Y-m-d");
$d = $d->add($oneday);
if ($d->getTimestamp() <= $endTimestamp) {
$res[] = $d->format("Y-m-d");
}
$d = $d->add($sixdays);
}
示例与
$end = new DateTime("2010-08-20");
$endTimestamp = $end->getTimestamp();
array(6) { [0]=> string(10) "2010-07-31" [1]=> string(10) "2010-08-01" [2]=> string(10) "2010-08-07" [3]=> string(10) "2010-08-08" [4]=> string(10) "2010-08-14" [5]=> string(10) "2010-08-15" }
这没有经过很好的测试,但它似乎工作得很好。 请注意,如果 $start 在周末而 $end 在一周的同一天但更早,则 $end 表示的日期将被省略 - 因此时间戳最好在午夜。
<?php
$start = $now = 1280293200; // starting time
$end = 1283014799; // ending time
$day = intval(date("N", $now));
$weekends = array();
if ($day < 6) {
$now += (6 - $day) * 86400;
}
while ($now <= $end) {
$day = intval(date("N", $now));
if ($day == 6) {
$weekends[] += $now;
$now += 86400;
}
elseif ($day == 7) {
$weekends[] += $now;
$now += 518400;
}
}
echo "Weekends from " . date("r", $start) . " to " . date("r", $end) . ":\n";
foreach ($weekends as $timestamp) {
echo date("r", $timestamp) . "\n";
}
对于发现这一点的其他人 - 我使用了以下内容:
$start = new DateTime($this->year.'-'.$month.'-01');
$interval = new DateInterval('P1D');
$end = new DateTime($this->year.'-'.$month.'-31');
$period = new DatePeriod($start,$interval,$end);
foreach ($period as $day){
if ($day->format('N') == 6 || $day->format('N') == 7){
$compulsory[$day->format('d')] = true;
}
}
修改您自己的开始范围和结束范围,而不是仅格式化 $compulsory 中的 d - 您可以执行 d/m/Y 以获得更重要的日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.