我正在尝试构建一个php函数,该函数将返回一个数组,其中包含最后n周的开始日期和结束日期。这将包括本周。它看起来像这样:
function lastnweeks(n)
{
//the code. I am not asking for the code itself but ideas on how to accomplish this
return $array;
}
$lastnweeks =lastnweeks(2);
print_r($lastnweeks);
这会打印出来:
Array (
[0] => Array (
[0] => 2010/09/20
[1] => 2010/09/26
)[1] => Array (
[0] => 2010/09/13
[1] => 2010/09/19
))
答案 0 :(得分:2)
由于夏令时和leapyears / leapseconds,我不会使用绝对秒数。你可以让PHP的strtotime()
函数通过使用相对日期为你处理这个问题。通过循环的每次迭代,您只需告诉函数找到“上周一”,然后使用该结果作为下一次迭代的起点。
代码:
$past_weeks = 7;
$relative_time = time();
$weeks = array();
for($week_count=0;$week_count<$past_weeks;$week_count++) {
$monday = strtotime("last Monday", $relative_time);
$sunday = strtotime("Sunday", $monday);
$weeks[] = array(
date("Y-m-d", $monday),
date("Y-m-d", $sunday),
);
$relative_time = $monday;
}
var_dump($weeks);
输出:
array
0 =>
array
0 => string '2010-09-20' (length=10)
1 => string '2010-09-26' (length=10)
1 =>
array
0 => string '2010-09-13' (length=10)
1 => string '2010-09-19' (length=10)
2 =>
array
0 => string '2010-09-06' (length=10)
1 => string '2010-09-12' (length=10)
3 =>
array
0 => string '2010-08-30' (length=10)
1 => string '2010-09-05' (length=10)
4 =>
array
0 => string '2010-08-23' (length=10)
1 => string '2010-08-29' (length=10)
5 =>
array
0 => string '2010-08-16' (length=10)
1 => string '2010-08-22' (length=10)
6 =>
array
0 => string '2010-08-09' (length=10)
1 => string '2010-08-15' (length=10)
答案 1 :(得分:0)
使用strtotime
获取星期一,然后减去每周的秒数:
function lastnweeks($n) {
$time = strtotime('Monday 00:00:00+0000');
$arr = array();
while ($n-- > 0) {
$arr[] = array_reverse(array(
date('Y/m/d', $time-=86400), // sunday
date('Y/m/d', $time-=6*86400) // monday
));
}
return $arr;
}
array_reverse
用于在计算倒退时反转数组。
答案 2 :(得分:0)
选择
$last_week = strtotime('last Week');
echo "Last Week ".date("Y/m/d", $last_week)."<br />\n";
或
$last_week = mktime(0,0,0,date("m"),date("d")-7,date("Y"));
echo "Last Week ".date("Y/m/d", $last_week)."<br />\n";