我正在尝试向用户显示用户友好的日期格式,例如“1小时15分钟”,“4天8小时”。但是由于某种原因,我的脚本显示0小时为23小时。
$date = '2014-01-15 15:00' # PAST DATE
$now = Date("Y-m-d H:m:s");
$seconds = strtotime($now) - strtotime($date);
$days = floor($seconds / 86400);
$hours = floor(($seconds - ($days * 86400)) / 3600);
$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));
if($days > 0)
{
if($days == 1)
{
return $days . ' dag ' . $hours . ' timmar';
} else {
return $days . ' dagar ' . $hours . ' timmar';
}
}
if(($hours < 24) AND ($hours > 0))
{
return $hours . ' timmar';
}
if($minutes < 60)
{
return $minutes . ' minuter';
}
任何人都可以看到导致这种情况的原因吗?我这样做是正确的吗?请注意,$ date是过去用户提供的。
答案 0 :(得分:3)
有更简单的方法可以做到这一点:
$past = new DateTime('2014-01-15 15:00');
$now = new DateTime();
$interval = $now->diff($past);
echo $interval->format('%y years, %m months, %d days,
%h hours, %i minutes, %S seconds');
显而易见的改进是现在使用显示零值(即0天)的时间段:
$elapsed = $interval->format('%y years, %m months, %d days,
%h hours, %i minutes');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,',
' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ',
' 1 hours, ', ' 1 minutes'), array('1 year, ',
'1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'),
$elapsed);
答案 1 :(得分:0)
使用类似的东西:
$date = '2014-01-15 15:00' # PAST DATE
now = Date("Y-m-d H:m:s");
$t = strtotime($now) - strtotime($date);
$time = date('g:iA M dS', $t );
$diff = time() - $t;
if ( $diff < 60 )
{
return "a few seconds ago";
}
elseif ( $diff < 3600 )
{
return "about ".( int ) ($diff/60) ." mins ago";
}
elseif ( $diff < 86400 )
{
if ( ( int ) ($diff/3600) == 1 )
{
return "about an hour ago";
}
else
{
return "about ".( int ) ($diff/3600) ." hours ago";
}
}
else if( $diff < 172800 )
{
return "about a day ago";
}
elseif ( $diff > 172800 )
{
return "$time";
}