user892134
user892134

Reputation: 3214

Time ago function php

I'm trying to do a time ago function only going back 24 hours. So the values returned will be random like;

I'm trying to amend this function but don't know how to limit how to limit only going back 24 hours.

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";
        }
    }
}

How do i solve this?

Upvotes: 1

Views: 601

Answers (3)

Maks3w
Maks3w

Reputation: 6459

Use DateTime.diff and use the properties for 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";
    }
}

Upvotes: 0

harrrrrrry
harrrrrrry

Reputation: 14507

After the line $hours = round($time_elapsed / 3600);, add if($hours > 24) return;, then you can limit the hours fewer than 24.

Upvotes: 0

Al.G.
Al.G.

Reputation: 4426

You do not need such complex things.
This is enough:

$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';

Upvotes: 1

Related Questions