我在php中有两个日期变量
$ var1和$ var2
var1包含一些过去时间,var2包含当前时间。我想计算相对时间,例如3小时前,5天前等等。
我已经被困了很长一段时间。任何人都可以帮忙
我已经提到了有关此问题的现有stackoverflow帖子,但它对我没有帮助。
答案 0 :(得分:0)
您可以calculate difference然后convert to natural language。并尝试下次在StackOverflow上使用搜索字段;)
答案 1 :(得分:0)
这是我回过头来写的一个函数:
function relative_date($timestamp) {
// calculate time difference
$timediff = time() - $timestamp;
switch($timediff) {
// less than a minute, show seconds
case $timediff <= 60:
$seconds = $timediff;
$str = $timediff . ($timediff == 1 ? " second ago" : " seconds ago");
break;
// less than a hour, show minutes
case $timediff <= 3600:
$minutes = floor($timediff / 60);
$str = $minutes . ($minutes == 1 ? " minute ago" : " minutes ago");
break;
// less than a day, show hours
case $timediff <= 86400:
$hours = floor($timediff / 3600);
$str = $hours . ($hours == 1 ? " hour ago" : " hours ago");
break;
// less than a year, show days
case $timediff <= (86400 * 365):
$days = floor($timediff / 86400);
$str = $days . ($days == 1 ? " day ago" : " days ago");
break;
// over a year, just show years
default:
$years = floor($timediff / (86400 * 365));
$str = $years . ($years == 1 ? " year ago" : " years ago");
}
return $str;
}