周期:日、周、月、年
间隔:1、2、3、4、5、6......
例子:间隔为“2”,周期为“周”,得出结果为:本周【本周一】的开始日期和下周【下周日】的结束日期,分别为"2021-05-03 00:00" "2021-05-16 23:59"
简单的使用PHP内置函数封装了一个函数,如下:
/**
* 获取开始和结束时间戳(根据周期[日 周 月 年]及间隔[1 2 3 ...])
* @param $timePeriod 周期
* @param $timeInterval 间隔
* @return array
*/
public static function getStartAndEndTime($timePeriod, $timeInterval)
{
if ($timePeriod === 1) {
//日
$dateStart = strtotime(date('Y-m-d'));
$dateEnd = strtotime(date('Y-m-d') . "+{$timeInterval} day") - 1;
} elseif ($timePeriod === 2) {
//周
$num = $timeInterval - 1;
$dateStart = strtotime(date("Y-m-d H:i:s", strtotime("this week Monday",time())));
$dateEnd = strtotime(date("Y-m-d 23:59:59", strtotime("this week Sunday",strtotime("+{$num} week"))));
} elseif ($timePeriod === 3) {
//月
$monthFirstDay = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y")));
$dateStart = strtotime($monthFirstDay);
$dateEnd = strtotime($monthFirstDay ."+{$timeInterval} month -1 day" );
} elseif ($timePeriod === 4) {
//年
$num = $timeInterval - 1;
$dateStart = strtotime(date('Y-01-01 00:00:00'));
$dateEnd = strtotime(date('Y-12-31 23:59:59') . "+{$num} year");
}
$return = [
'start_at' => $dateStart,
'end_at' => $dateEnd,
'start_time' => self::dateJudge($dateStart, 'Y-m-d H:i'),
'end_time' => self::dateJudge($dateEnd, 'Y-m-d H:i')
];
return $return;
}
/**时间戳转字符串时间
* @param $time
* @param string $format 日期格式
* @return bool|string
*/
public static function dateJudge($time, $format = 'Y-m-d H:i:s')
{
return empty($time) ? '' : date($format, $time);
}