PHP时间戳小时到天

时间:2017-05-21 11:52:58

标签: php

我有一个时间戳,我需要返回:

当它不到1小时时,我需要它说“30分钟前”。 当它不到24小时我需要它说“6小时前”。 当它达到24小时后,我需要它说“1天前”。 当它达到48小时后,我需要它说“2天前”。

是否可以使用条件语句完成?

到目前为止,我可以返回天数:

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

2 个答案:

答案 0 :(得分:2)

我猜您可以使用DateTimeDateIntervalDatePeriod

$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 :(得分: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 );

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 ); 你会得到几分钟和几个小时,相应地说明你的情况