使用php查找月份中的特定星期 [英] find specific weeks in month using php

查看:175
本文介绍了使用php查找月份中的特定星期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从星期一开始的月份开始,直到当月的星期日结束. 我将提供月份和年份. 例如:

I am tring to get the week from the month having starting Monday and end with Sunday with in same month. i'll provide month and year. for example:

$month = '03';
$year = '2014';

然后函数应该返回 2014-03-03 to 2014-03-09作为月份的开始日期,因为该月的第一个星期一为3月. 然后继续一个月直到上周. 2014年3月,第31日从星期一开始,但没有在3月结束,它在2014年6月4日结束,因此不应计入此中.

then function should return 2014-03-03 to 2014-03-09 as start date of month coz the month has its first Monday on 3rd. then continue to month till last week. In march, 2014, 31st starts on Monday but don't finish in march, it finishes at 06-04-2014 so this should not be included in counting.

现在,当我将月份作为"04"通过时,该月份应在其第一周的3月31日算起.

Now, when i pass month as '04' than the month should count 31st march in its first week.

我希望我能表明自己的意思,对不起语言. 到目前为止,我已经尝试过:

I hope i make my self clear, sorry for language. I have tried so far:

$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
)

推荐答案

<?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
)

查看实际效果

这篇关于使用php查找月份中的特定星期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆