日期操作
一、根据日期生成日期数组
/*** 根据指定日期生成日期数组* @param $start_time 开始时间* @param $end_time 结束时间* @return array 返回数组结果*/
function createDateArr($start_time, $end_time)
{$open_start_time = $start_time;$open_end_time = $end_time;$stimestamp = strtotime($open_start_time);$etimestamp = strtotime($open_end_time);// 计算日期段内有多少天$days = ($etimestamp - $stimestamp) / 86400 + 1;// 保存每天日期$arr = [];for ($i = 0; $i < $days; $i++) {$arr[] = date('Y-m-d', $stimestamp + (86400 * $i));}return $arr;
}
//调用示例
$start_time='2024-05-12';
$end_time='2024-05-15';
$data=createDateArr($start_time,$end_time);
//结果
Array
([0] => 2024-05-12[1] => 2024-05-13[2] => 2024-05-14[3] => 2024-05-15
)
二、根据指定日期获取月份数组
/*** 根据指定日期生成月份数组* @param $startDate* @param $endDate* @return array* @throws Exception*/
function generateMonthlyArray($startDate, $endDate) {$start = new DateTime($startDate);$end = new DateTime($endDate);$end->modify('last day of this month');$interval = new DateInterval('P1M');$period = new DatePeriod($start, $interval, $end);$monthlyArray = array();foreach ($period as $month) {$monthlyArray[] = $month->format('Y-m');}return $monthlyArray;
}
//调用示例
$start_time='2024-05-12';
$end_time='2024-12-15';
$data=generateMonthlyArray($start_time,$end_time);
//结果
Array
([0] => 2024-05[1] => 2024-06[2] => 2024-07[3] => 2024-08[4] => 2024-09[5] => 2024-10
)
三、周日期转换
时间转换
一、将日期转换成距今多长时间
/*** 将日期转换成距今多长时间* @param $show_time 日期时间* @param $now_time 当前时间* @return false|int|string*/
function time_distance($show_time)
{if (!$show_time) {return '';}$show_time = (!is_numeric($show_time)) ? strtotime($show_time) : $show_time;$now_time = time();$dur = $now_time - $show_time;if ($dur < 0) {return $show_time;} else {if ($dur < 10) {return '刚刚';} else if ($dur < 60) {return $dur . '秒前';} else {if ($dur < 3600) {return floor($dur / 60) . '分钟前';} else {if ($dur < 86400) {return floor($dur / 3600) . '小时前';} else {return date_change($show_time);}}}}
}//转变时间
function date_change($date)
{if (!$date) {return '';}$date = (!is_numeric($date)) ? strtotime($date) : $date;if (date('Ymd', $date) == date('Ymd', time())) {return date('H:i', $date);} else if (date('Ymd', $date) == date('Ymd', strtotime('-1 day'))) {return "昨天 " . date('H:i', $date);} else if (date('Y', $date) == date('Y', time())) {return date('m月d日', $date);} else {return date('Y年m月d日', $date);}
}
//示例
$start_time='2024-05-31 16:23:56';
$data= time_distance($start_time);
//结果
55分钟前
1小时前