我正在开发一个php应用程序,它要求我在两个日期之间提取周末的日期,然后将它们作为单个记录插入到mysql数据库中。
我在想是否有更简单的方法,而不是经历开始日期和结束日期之间的循环,以及每个日期检查date('l', strtotime($date))
是否返回“星期六”或“星期日”
感谢您的时间
苏尼
答案 0 :(得分:11)
如果您使用较旧的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
索引(星期日或星期六)。
答案 1 :(得分:6)
那么php日期(“N”)会给你一周中的一天,其中1表示星期一,7表示星期日,所以你可以很容易地将它变成if语句。
答案 2 :(得分:3)
$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" }
答案 3 :(得分:0)
这没有经过充分测试,但似乎工作得很好。请注意,如果$ 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";
}
答案 4 :(得分:0)
For anyone else that finds this - I have used the following:
$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;
}
}
Amend to your own start range and end range and rather than format just the d in $compulsory - you could do d/m/Y for a more substantial date.