本文实例讲述了PHP常用函数之格式化时间操作。分享给大家供大家参考,具体如下:
/** * 格式化时间 * @param $time 时间戳 * @return bool|string */ function formatTimeToNow($time){ //获取现在的时间戳 $nowtime = time(); if($time>$nowtime){ return ''; }else{ $tc = $nowtime-$time; if( $tc >= 864000 ){ $str = date('Y-m-d H:i',$time);//如果大于10天,则直接显示日期 }else if( $tc >= 86400){ $str = floor($tc/86400) . "天前";//如果大于1天 }else if( $tc >= 3600) { $str = floor($tc / 3600) . "小时前";//如果大于1小时 }else if( $tc >= 60) { $str = floor($tc / 60) . "分钟前";//如果大于1分钟 }else{ $str = "刚刚"; } return $str; } }
/** * 将中文的日期格式化为正常的日期 * @param $date * @return mixed */ function formatCnDateToDate($date){ //把年月替换为-,日替换为空 $date = str_replace('年','-',$date); $date = str_replace('月','-',$date); $date = str_replace('日','',$date); //避免提交的格式不统一,例如2018-3-2等,标准化 return date('Y-m-d',strtotime($date)); }
/** * 计算自然周期的开始时间戳和结束时间戳(周一到周日,月初到月末) * @param int $time_type 1表示自然天,2表示自然周,3表示自然月 * @param int $prev_num 距离现在的值(前一周传-1,前两周传-2...) * @return array|bool */ function naturalFormatTime($time_type=1,$prev_num=0){ $today_start_time = strtotime(date('Y-m-d 00:00:00',time()));//今天0点的时间戳 if($time_type == 1){ if($prev_num == 0){ return array('start_time'=>$today_start_time,'end_time'=>time(),'show_date'=>date('Y年m月d日',time())); }else if($prev_num < 0){ $start_time = $today_start_time - 86400*abs($prev_num); $end_time = $start_time + 86399; $show_date = date('Y年m月d日',$start_time); return array('start_time'=>$start_time,'end_time'=>$end_time,'show_date'=>$show_date); }else{ return false; } }else if($time_type == 2){ $today_week = date('w',$today_start_time); if($today_week == 0){ $today_week_start_time = $today_start_time - 86400*6; }else{ $today_week_start_time = $today_start_time - 86400*($today_week-1); } if($prev_num == 0){ $show_date = date('Y年m月d日',$today_week_start_time); $show_date .= '至' . date('d日',time()); return array('start_time'=>$today_week_start_time,'end_time'=>time(),'show_date'=>$show_date); }else if($prev_num < 0){ $start_time = $today_week_start_time - 86400*7 * abs($prev_num); $end_time = $start_time + (86400*7-1); $show_date = date('Y年m月d日',$start_time); $show_date .= '至' . date('d日',$end_time); return array('start_time'=>$start_time,'end_time'=>$end_time,'show_date'=>$show_date); }else{ return false; } }else if($time_type == 3){ if($prev_num == 0){ $today_day = ltrim(date('d',$today_start_time),0); $today_month_start_time = $today_start_time - 86400*($today_day-1); $show_date = date('Y年m月d日',$today_month_start_time); $show_date .= '至' . date('d日',time()); return array('start_time'=>$today_month_start_time,'end_time'=>time(),'show_date'=>$show_date); }else if($prev_num < 0){ $start_time = strtotime(date('Y-m-01', strtotime("$prev_num month"))); $days = date('t',$start_time); $end_time = $start_time + 86400 * $days -1; $show_date = date('Y年m月d日',$start_time); $show_date .= '至' . date('d日',$end_time); return array('start_time'=>$start_time,'end_time'=>$end_time,'show_date'=>$show_date); }else{ return false; } }else{ return false; } }