我想从星期一开始的那个月开始,并在同一个月的星期日结束。 我会提供月份和年份。 例如:
$month = '03';
$year = '2014';
那么函数应该返回
2014-03-03 to 2014-03-09
作为月份的开始日期,月份的第一个星期一是3月。
然后继续到上个月到上周。
在2014年3月,31日从星期一开始,但没有在3月完成,它在2014年4月6日结束,所以这不应该计入。
现在,当我将月份作为'04'而不是月份时应该在第一周的31日进行计数。
我希望我清楚自己,对不起语言。 到目前为止我已尝试过:
$month = "04";
$year = "2014";
$beg = (int)date('W', strtotime("first day of $year-$month"));
$end = (int)date('W', strtotime("last day of $year-$month"));
$weeks = range($beg, $end);
foreach($weeks as $week) {
$result = $this->getStartAndEndDate($week, $year);
print_r($result);
}
function getStartAndEndDate($week, $year)
{
$time = strtotime("1 January $year", time());
$day = date('w', $time);
$time += ((7*$week)+1-$day)*24*3600;
$return[0] = date('Y-m-d', $time);
$time += 6*24*3600;
$return[1] = date('Y-m-d', $time);
return $return;
}
输出:
Array
(
[0] => 2014-03-03
[1] => 2014-03-09
)
Array
(
[0] => 2014-03-10
[1] => 2014-03-16
)
Array
(
[0] => 2014-03-17
[1] => 2014-03-23
)
Array
(
[0] => 2014-03-24
[1] => 2014-03-30
)
Array
(
[0] => 2014-03-31
[1] => 2014-04-06
)
Array
(
[0] => 2014-04-07
[1] => 2014-04-13
)
答案 0 :(得分:0)
您可以使用DateTime
类:
$dt = new DateTime('1st march');
// is this a monday?
if($dt->format('N') !== '1') {
// if not, went to next monday
$dt->modify('next monday');
}
echo $dt->format('Y-m-d')
. ' to ' . $dt->modify('next sunday')->format('Y-m-d');
输出:
2014-03-03 to 2014-03-09
答案 1 :(得分:0)
<?php
function get_weeks($month, $year) {
$weeks = array();
$date = DateTime::createFromFormat('mY', $month.$year);
$date->modify('first Monday of this month');
$end = clone $date;
$end->modify('last Monday of this month');
$interval = DateInterval::createFromDateString('1 week');
$period = new DatePeriod($date, $interval, $end);
$counter = 1;
foreach ($period as $dt) {
$end_of_week = clone $dt;
$end_of_week->modify('next Sunday');
$weeks[] = sprintf("Week %u: %s - %s",
$counter,
$dt->format('Y-m-d'),
$end_of_week->format('Y-m-d')
);
$counter++;
}
return $weeks;
}
$weeks = get_weeks('03', '2014');
print_r($weeks);
Array
(
[0] => Week 1: 2014-03-03 - 2014-03-09
[1] => Week 2: 2014-03-10 - 2014-03-16
[2] => Week 3: 2014-03-17 - 2014-03-23
[3] => Week 4: 2014-03-24 - 2014-03-30
)