获取某个周在本年的开始日期和结束日期

传入 年份 和 本年的多少,计算改周在本年的开始日期和结束日期

/*
 * @Purpose    :    根据所给年份和该年的第几周,得出该周在本年的开始日期和结束日期
 * @time    :    2017/11/03
*/
function getWeekStartAndEnd ($year,$week=1) {
    header("Content-type:text/html;charset=utf-8");
    date_default_timezone_set("Asia/Shanghai");
    $year = (int)$year;
    $week = (int)$week;
    //按给定的年份计算本年周总数
    $date = new DateTime;
    $date->setISODate($year, 53);    // 参见 http://php.net/manual/zh/datetime.setisodate.php
    // 一年周的最大值为 52
    $weeks = max($date->format("W"),52);    // $date->format("W") 将日期格式化为 周,
    //如果给定的周数大于周总数或小于等于0
    if($week>$weeks || $week<=0){
        return false;
    }
    //如果周数小于10
    if($week<10){
        $week = '0'.$week;
    }
    //当周起止时间戳
    $timestamp['start'] = strtotime($year.'W'.$week);    // strtotime('2009W32');Get timestamp of 32nd week in 2009. 参见:http://cn2.php.net/manual/zh/function.strtotime.php    
    $timestamp['end'] = strtotime('+1 week -1 day',$timestamp['start']);
    //当周起止日期
    $timeymd['start'] = date("Y-m-d",$timestamp['start']);
    $timeymd['end'] = date("Y-m-d",$timestamp['end']);
    
    //返回起始时间戳
    //return $timestamp;
    //返回日期形式
    return $timeymd;
 }
 
 $week_time = getWeekStartAndEnd(2017,10);
 var_dump($week_time);

 //array (size=2)
 // 'start' => string '2017-03-06' (length=10)
 // 'end' => string '2017-03-12' (length=10)

参考自http://www.thinkphp.cn/topic/4491.html

 

posted @ 2017-11-03 17:53  Chrdai  阅读(328)  评论(0编辑  收藏  举报