2017-05-21 7 views
1

返す必要があるタイムスタンプがあります。PHPのタイムスタンプの時間数

「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); 

これを使用して分と時間を得て、それに応じて条件を入力してください

関連する問題