前一段时间功能php

时间:2015-02-08 17:39:10

标签: php

我试图做一次以前的功能只能回到24小时。因此返回的值将是随机的;

  • 7分钟前;

  • 2小时39分钟前;

  • 5小时前;

我试图修改此功能,但不知道如何限制如何限制只能回到24小时。

function timeAgo($time_ago){
$cur_time   = time();
$time_elapsed   = $cur_time - $time_ago;
$seconds    = $time_elapsed ;
$minutes    = round($time_elapsed / 60 );
$hours      = round($time_elapsed / 3600);
// Seconds
    if($seconds <= 60){
        echo "$seconds seconds ago";
    }
    //Minutes
    else if($minutes <=60){
        if($minutes==1){
            echo "one minute ago";
        }
        else{
            echo "$minutes minutes ago";
        }
    }
    //Hours
    else if($hours <=24){
        if($hours==1){
            echo "an hour ago";
        }else{
            echo "$hours hours ago";
        }
    }
}

我如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

你不需要这么复杂的事情 这就足够了:

$hours = rand(0, 3);
$mins = rand(0, 59);
$secs = rand(0, 59);
$text = '';
if ($hours) $text = $hours . ' hours';
if ($mins) $text .= $mins . ' mins';
if ($secs) $text .= $secs . ' secs';

// The following is almost impossible to happen, but anyway...
if (!$hours && !$mins && !$secs) $text = rand(1, 59) . ' mins';

$text .= 'ago';

答案 1 :(得分:0)

$hours = round($time_elapsed / 3600);行之后添加if($hours > 24) return;,然后您可以将小时数限制为少于24小时。

答案 2 :(得分:0)

使用DateTime.diff并使用DateInterval

的属性
function timeAgo(DateTime $time_ago){
$cur_time   = new DateTime();
$time_elapsed   = $cur_time.diff($time_ago);
$seconds    = $time_elapsed.s;
$minutes    = $time_elapsed.i;
$hours      = $time_elapsed.h;
$days       = $time_elapsed.d;

    //days
    if($days > 1){
        if($days==1){
            echo "one day ago";
        }else{
            echo "$days days ago";
        }
    }
    //Hours
    else if($hours > 1){
        if($hours==1){
            echo "an hour ago";
        }else{
            echo "$hours hours ago";
        }
    }
    //Minutes
    else if($minutes > 0){
        if($minutes==1){
            echo "one minute ago";
        }
        else{
            echo "$minutes minutes ago";
        }
    }
    // Seconds
    else if($seconds> 0){
        echo "$seconds seconds ago";
    }
}