简体   繁体   中英

How to detect if current date is greater than datetime?

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 .

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM