目录
近七天(支持过去七天和未来七天,具体天数可根据需求调整)
if(!function_exists('getSevenDate')){
/**
* 获取最近七天所有日期
* @param string $time 时间戳
* @param string $format 格式化
* @param string $operation 运算符 +表示某日期过去七天,-表示某日期未来七天
* @return array 日期数组
*/
function getSevenDate($time = '', $format='Y-m-d', $operation='+'){
$time = $time != '' ? $time : time();
//组合数据
$date = [];
for ($i=1; $i<=7; $i++){
$date[$i] = date($format ,strtotime( "{$operation}" . $i-7 .' days', $time));
}
return $date;
}
}
计算近N天所有日期并返回其数组
if (!function_exists('getEveryDayByRecentDate')) {
/**
* 生成近N天具体日期
* @param int $dayNum 生成最近天数
* @param string $fmt 生成的日期格式
* @return array 返回具体的日期数组
*/
function getEveryDayByRecentDate($dayNum, $fmt = 'Y-m-d') {
$days = [];
for ($i = 0; $i < $dayNum; $i++) {
$days[] = date($fmt, strtotime(' -'. $i . 'day'));
}
return $days;
}
}
计算两日期之间所有日期并返回其数组
if (!function_exists('dayAryByTwoDate')) {
/**
* 计算两个日期之间所有每天的日期并作为数组返回
* @param int $days 生成日期数量
* @param string $startDate 开始日期日期(不传则以当前时间计算,日期时间格式)
* @return array $datAry 日期数组
* @throws Exception
*/
function dayAryByTwoDate(int $days, $startDate = 'now')
{
$datetime = new \DateTime($startDate);
$interval = \DateInterval::createFromDateString('+1 day');
$period = new \DatePeriod($datetime, $interval, $days);
$datAry = [];
foreach ($period as $date) {
$datAry[] = $date->format('Y-m-d');
}
return $datAry;
}
}
计算两日期之间相差的天数
if(!function_exists('diffBetweenTwoDays'))
{
/**
* 求两个日期之间相差的天数
* (针对1970年1月1日之后,求之前可以采用泰勒公式)
* @param string $day1
* @param string $day2
* @return number
*/
function diffBetweenTwoDays(string $day1, string $day2)
{
//$second1 = strtotime(date('Y-m-d', strtotime($day1)));
//$second2 = strtotime(date('Y-m-d', strtotime($day2)));
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
return floor(($second1 - $second2) / 86400);
}
}
***************************只要思想不滑坡,办法总比困难多***************************