## **簡介**
時間轉換函數也是我們在日常編碼中常用的,即時是在強大的laravel中也有很多的時間處理類,我們在這里只是提供一些自己定義的時間處理函數。
1.計算距離現在的時間
```
/**
* 傳入時間戳,計算距離現在的時間
* @param number $time 時間戳
* @return string 返回多少以前
*/
function word_time($time) {
$time = (int) substr($time, 0, 10);
$int = time() - $time;
$str = '';
if ($int <= 2){
$str = sprintf('剛剛', $int);
}elseif ($int < 60){
$str = sprintf('%d秒前', $int);
}elseif ($int < 3600){
$str = sprintf('%d分鐘前', floor($int / 60));
}elseif ($int < 86400){
$str = sprintf('%d小時前', floor($int / 3600));
}elseif ($int < 1728000){
$str = sprintf('%d天前', floor($int / 86400));
}else{
$str = date('Y-m-d H:i:s', $time);
}
return $str;
}
```
```
/**
* 傳入時間戳,計算距離現在的時間
* @param number $the_time 時間戳
* @return string 返回多少以前
*/
function formatTime($the_time)
{
$now_time = time();
$dur = $now_time - $the_time;
if ($dur < 0) {
return $the_time;
} else {
if ($dur < 60) {
return $dur . '秒前';
} else {
if ($dur < 3600) {
return floor($dur / 60) . '分鐘前';
} else {
if ($dur < 86400) {
return floor($dur / 3600) . '小時前';
} else {//昨天
//獲取今天凌晨的時間戳
$day = strtotime(date('Y-m-d', time()));
//獲取昨天凌晨的時間戳
$pday = strtotime(date('Y-m-d', strtotime('-1 day')));
if ($the_time > $pday && $the_time < $day) {//是否昨天
return $t = '昨天 ' . date('H:i', $the_time);
} else {
if ($dur < 172800) {
return floor($dur / 86400) . '天前';
} else {
return date('Y-m-d H:i', $the_time);
}
}
}
}
}
}
}
```
2.獲取指定日期段內每一天的日期get_date_from_range('2017-8-8','2018-9-9')
```
/**
* 獲取指定日期段內每一天的日期
* @param Date $startdate 開始日期
* @param Date $enddate 結束日期
* @return Array
*/
function get_date_from_range($startdate, $enddate)
{
$stimestamp = strtotime($startdate);
$etimestamp = strtotime($enddate);
// 計算日期段內有多少天
$days = ($etimestamp-$stimestamp)/86400+1;
// 保存每天日期
$date = [];
for($i=0; $i<$days; $i++) {
$date[] = date('Y-m-d', $stimestamp+(86400*$i));
}
return $date;
}
```
3.where語句查詢是前端返回2018-12-20 13:56:00 - 2018-12-21 13:56:00
```
function timeData($time){
$n = 0;
for($i = 1;$i <= 3;$i++) {
$n = strpos($time,'-',$n);
$i != 3 && $n++;
}
$kaddtime=strtotime(trim(substr($time,0,$n)));
$xaddtime=strtotime(trim(substr($time,$n+1)));
$where = [['>',$kaddtime],['<',$xaddtime]];
return $where;
}
function timess($time){
$n = 0;
for($i = 1;$i <= 3;$i++) {
$n = strpos($time,'-',$n);
$i != 3 && $n++;
}
$kaddtime=strtotime(trim(substr($time,0,$n)));
$xaddtime=strtotime(trim(substr($time,$n+1)));
return [$kaddtime,$xaddtime];
}
```