簡體   English   中英

如何檢測當前日期是否大於datetime?

[英]How to detect if current date is greater than datetime?

實際上我想創建一個函數,如果日期大於1,則返回日期,它應該像1小時前一樣返回時間年齡。

我已經完成了近80%的Time Ago功能,現在我想添加一個功能。

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

}

請查看輸出,這可能有助於理解我的問題。

如果日期小於1,那么它正常工作// 1 min ago1 hour ago現在我想添加如果日期大於1那么它應該以這種格式返回日期// 18 May 2015

你可以做的是通過getTimestamp()方法從你的日期時間( http://php.net/manual/fr/class.datetime.php )獲取時間戳,最后你可以相互比較它們

假設$ date是一個Datetime實例:

$time = time() - $time->getTimestamp();

實際上,我在我的函數中添加了if語句,現在它正在工作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM