4

Actually I'd like to create a function which return me the date if the day is greater than one and it should return the time age like 1 hour ago.

I have done almost 80%, Time Ago functionality now I want to add one more feature.

function dateTimeExe ($time)
{

    $time = time() - $time; // to get the time since that moment

    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }

}

Please view output it may help to understand my question.

If day is less than 1 then it is working properly // 1 min ago or 1 hour ago Now I want to add if day is greater than 1 then it should return date in this format // 18 May 2015.

moffeltje
  • 4,521
  • 4
  • 33
  • 57
ayaz khan
  • 141
  • 8

2 Answers2

0

What you can do is getting the timestamp from your datetime (http://php.net/manual/fr/class.datetime.php) thanks to getTimestamp() method and finally you can compare them with each other

Assuming $date is a Datetime instance :

$time = time() - $time->getTimestamp();
Cr3aHal0
  • 809
  • 4
  • 11
0

Actually, I add if statement in my function and now its working

if ($time>86400) {
        return date('d F Y');
    }else{
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
        }
    }
ayaz khan
  • 141
  • 8
  • 2
    yes, that's almost exactly what I have put in my answer which someone downvoted. Almost, because you should return `date('d F Y', $original_time)` - date of given time, not today's date! BTW, your answer should be a comment, possibly under your question or under answer which says the same thing. – n-dru May 18 '15 at 09:54