2015-12-27 130 views
2

這裏是我的功能:日期比較只考慮時間(PHP)

function hasTimeElapsed($date, $time) { 
    if (new DateTime() > new DateTime($date.' '.$time)) { 
     return true; 
    } else { 
     return false; 
    } 
} 

$date輸入當屬2015-12-29(MySQL的格式),並且$time輸入當屬04:00:00(MySQL的格式)。例如,現在是3:10。如果$time是3:11,則它會過期,完全忽略日期不同的事實(29,而不是27)。如何準確檢查時間是否已過,包括實際的日期?

回答

3

這可能不是答案,太長了評論;我無法複製你正在觀察的內容。下面是我使用的存根:

<?php 
date_default_timezone_set('America/Chicago'); 

$tests = array(
    array('2015-12-25', '04:00:00'), 
    array('2015-12-26', '04:00:00'), 
    array('2015-12-27', '04:00:00'), 
    array('2015-12-28', '04:00:00'), 
    array('2015-12-29', '04:00:00'), 
); 

$now = new DateTime('2015-12-27 03:11:10'); 
print 'Current time: ' . $now->format('Y-m-d H:i:s') . "\n"; 

foreach ($tests as $dt) { 
    print sprintf("%s %s => %s\n", 
     $dt[0], 
     $dt[1], 
     hasTimeElapsed($dt[0], $dt[1], $now) ? 'T' : 'F' 
    ); 
} 

function hasTimeElapsed($date, $time, $now) { 
    $supplied = new DateTime($date.' '.$time); 
    return $now > $supplied; 
} 
?> 

結果如預期:如果

$ php test.php 
Current time: 2015-12-27 03:11:10 
2015-12-25 04:00:00 => T 
2015-12-26 04:00:00 => T 
2015-12-27 04:00:00 => F 
2015-12-28 04:00:00 => F 
2015-12-29 04:00:00 => F 

相同的結果我用的現任美國中部時間2015年12月26日23時39分10秒。你能用上面類似的存根檢查你的結果嗎?