Ericson Willians Ericson Willians - 4 years ago 62
SQL Question

Date comparison is considering only the time (PHP)

Here's my function:

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


That
$date
input comes as
2015-12-29
(MySQL format), and that
$time
input comes as
04:00:00
(MySQL format).

Now, for example, is 3:10. If that
$time
is 3:11, it expires ignoring completely the fact that the date is different (29, not 27). How can I accurately check if the time has elapsed including the actual date?

Answer Source

This may not be an answer and is too long for a comment; I am not able to replicate what you are observing. Here's the stub I am using:

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

Results are as expected:

$ 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

Same results if I use current US Central Time of 2015-12-26 23:39:10. Could you check your results with similar stub as above?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download