2017-05-21 59 views
1

我有一個時間戳,我需要返回爲:PHP時間戳小時至天

當它不到1小時,我需要它說「30分鐘前」。 當它在24小時內,我需要它說「6小時前」。 當它達到24小時,我需要它說「1天前」。 當它達到48小時,我需要它說「2天前」。

這是用條件語句來完成的嗎?

到目前爲止,我可以返回的天數:我想你可以使用DateTimeDateIntervalDatePeriod

$post_timestamp \t = strtotime($post_timestamp); 
 
$current_date = strtotime(time()); 
 
\t \t \t \t \t 
 
$datediff = $current_date - $post_timestamp; 
 
$days = floor($datediff/(60*60*24)); \t \t \t \t \t

+3

對於這個用例來看[Carbon](http://carbon.nesbot.com/docs/)可能是一個好主意。 –

+0

添加到Matt的評論,你正在尋找的方法是diffForHumans() –

回答

2

$date1 = new DateTime(); 
$date2 = DateTime::createFromFormat('U', $post_timestamp); # I assume a unix timestamp here 
//determine what interval should be used - 1 minute 
$interval = new \DateInterval('PT1M'); 
//create periods every minute between the two dates 
$periods = new \DatePeriod($date2, $interval, $date1); 
//count the number of objects within the periods 
$mins = iterator_count($periods); 


if ($mins < 60) 
{ 
    $say = "30 minutes ago"; 

} elseif ($mins >= 60 and $mins < 60 * 24) 
{ 
    $say = "6 hours ago"; 

} elseif ($mins >= 60 * 24 and $mins < 60 * 48) 
{ 
    $say = "1 day ago"; 

} elseif ($mins >= 60 * 48) 
{ 
    $say = "2 days ago"; 
} 

print $say; 
+1

非常感謝你。從那裏我可以計算出要打印的分鐘數和小時數 –

+0

非常歡迎你@SSAM –

1

您可以使用類似的代碼如下:

date_default_timezone_set('Asia/Calcutta'); 
$post_timestamp="2017-05-21 5:00 pm"; 
$post_timestamp = strtotime($post_timestamp); 
$current_date = strtotime(date('Y-m-d h:i a'));     
$datediff = $current_date - $post_timestamp; 
$mins = ($datediff)/60; 
$hours = $datediff/(60 * 60); 

你會得到分鐘和小時數據,相應地將你的條件加入