簡體   English   中英

奇怪的PHP日期比較錯誤

[英]Strange PHP date comparison error

我沒有得到預期的結果。 基本上,我只想比較兩個日期(以Unix格式),並以月/日/小時/。來顯示差異。

這是代碼的摘錄:UPDATE-添加了更多代碼

$date = mktime($hour, $min, 0, $month, $day, $year);
$now = time();


echo 'OKdate' . $date . ' now ' . $now . ' now < date ' . ($now < $date);

if($now < $date)
{
    $difference = $date - $now;

    $seconds2 = date('s', $difference);
    $minutes2 = date('i', $difference);
    $hours2 = date('G', $difference) - 1;
    $days2 = date('j', $difference) - 1;
    $months2 = date('n', $difference) - 1;
    $years2 =  date('Y', $difference) - 1970;

    $timeleft = '';
    if(!empty($years2))
        $timeleft .= $years2 . ' year' . ($years2 > 1 ? 's ' : ' ');

    if(!empty($months2))
        $timeleft .= $months2 . ' month' . ($months2 > 1 ? 's ' : ' ');

    if(!empty($days2))
        $timeleft .= $days2 . ' day' . ($days2 > 1 ? 's ' : ' ');

    if(!empty($hours2))
        $timeleft .= $hours2 . ' hour' . ($hours2 > 1 ? 's ' : ' ');

    if(!empty($minutes2))
        $timeleft .= $minutes2 . ' minute' . ($minutes2 > 1 ? 's ' : ' ');

    if(!empty($seconds2))
        $timeleft .= $seconds2 . ' second' . ($seconds2 > 1 ? 's ' : ' ');

    $template = $templates->get('postcountdown_post', 1, 0);
    eval('$temp = "' . $template . '";');
    return $temp;
}

現在,這顯示在頁面上:

date = 1437950400 
now  = 1437935682 
now < date = true

奇怪的是,這是我通過回顯數據得到的結果:

11 months 30 days 22 hours 05 minutes 18 seconds left

謝謝您的幫助!

編輯:添加了更多代碼---僅供參考:模板內部包含{$ timeleft}。 因此,評估僅需確保{$ timeleft}已被PHP評估並填寫。

當前的問題:代碼似乎確實有效,但在應用程序中卻無效。 由於某些奇怪的原因,我得到$ difference = 12076; PHP的date函數為此提供了:-1年11個月……。另一個奇怪的事情是:它確實可以處理某些日期; 但是與其他人沒有關系,則為-1年。 -還是我的代碼中確實存在我看不到的缺陷?

date 1437954000 
now 1437942191 
now < date true
diff 11809
// $...2 variables
seconds 49 
mins 16 
hours 21 
days 30 
months 11 
years -1

上面的代碼在我的系統上按預期工作。 但是,在ini文件中未設置位置時,date函數可能會停止運行。 在PHP中,您可以使用以下命令設置服務器時區:

date_default_timezone_set ( "Europe/Brussels" );

其他時區可以在這里找到時區字符串

嘗試這個:

<?php

$now = 1437950400;
$date  = 1437935682; 

if($now > $date) {

$difference = $now - $date;

$seconds = date('s', $difference);
$minutes = date('i', $difference);
$hours = date('G', $difference) - 1;
$days = date('j', $difference) - 1;
$months = date('n', $difference) - 1;
$years =  date('Y', $difference) - 1970;

echo $years . ' Years ' 
    . $months . ' Months '
    . $days . ' Day '
    . $hours . ' Hours '
    . $minutes . ' Minutes '
    . $seconds . ' Seconds ';
}

暫無
暫無

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

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