PHP时间范围:本周、本月、下月等简写

在阅读TP5.1源码,发现其在时间范围上的写法很特别,个人第一次见,做一次记录

$timeRule = [
     'today'      => ['today', 'tomorrow'],
     'yesterday'  => ['yesterday', 'today'],
     'week'       => ['this week 00:00:00', 'next week 00:00:00'],
     'last week'  => ['last week 00:00:00', 'this week 00:00:00'],
     'month'      => ['first Day of this month 00:00:00', 'first Day of next month 00:00:00'],
     'last month' => ['first Day of last month 00:00:00', 'first Day of this month 00:00:00'],
     'year'       => ['this year 1/1', 'next year 1/1'],
     'last year'  => ['last year 1/1', 'this year 1/1'],
];

echo date('Y-m-d H:i:s', strtotime('this week 00:00:00'));
// 结果如下
2018-01-08 00:00:00

// 指定时间:本周第一天 + 1年2个月5天3小时5分钟
echo date('Y-m-d H:i:s', strtotime('this week 00:00:00 + 1year + 2month + 5day + 3hour + 5minute'));
// 返回结果
2019-03-13 03:05:00
// 根据年份中的第几周,获取周的开始时间,需要注意的是 $week 必须是2位数,不足前补0
strtotime($year . 'W' . $week);
echo strtotime('2018' . 'W' . '02');
//结果
2018-01-08

/**
* 根据【年,周】,获取时间范围
* @param $year
* @param int $week
* @return array|false
*/
function getWeekStartAndEnd ($year, $week = 1) {
$year = (int)$year;
$week = (int)$week;
$date = new \DateTime;
$date->setISODate($year, 53);
$weeks = max($date->format("W"),52);

//如果给定的周数大于周总数或小于等于0
if($week > $weeks || $week <= 0){
return false;
}

//如果周数小于10
if($week < 10){
$week = '0' . $week;
}

//当周起止时间戳
$startTime = strtotime($year . 'W' . $week);

//当周起止日期
$weekDate['start'] = date("Y-m-d", $startTime);
$weekDate['end'] = date("Y-m-d", $startTime + 7 * 24 * 3600 - 1);

return $weekDate;
}
posted @ 2018-01-08 17:55  cqingt  阅读(1254)  评论(0编辑  收藏  举报