简体   繁体   中英

Why isn't DateTime::sub working as expected?

Thanks to the answers to this question, I've managed to only output a list dates from my MySQL database that are in the future (ie after today) using PHP. However, what if I wanted to set 'today' back a little; in other words, if I want a date not to appear on the list of dates a week in advance?

I've attempted to use DateTime::sub using the following code, but it kills my script (I just get a blank screen - if I comment out the DateTime::sub line, it works again. I still haven't worked out how to get PDO to echo error details):

$dateToday = new DateTime('now');
$dateToday -> sub(new DateInterval('P7D'));

do{
    $dateCompare = new DateTime($row['date']);
    if ($dateCompare > $dateToday){
        echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
    } else {  
        echo '<p>FALSE</p>';
    }
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));

Any ideas?

You code works just fine for me, I imagine it's a problem with this line:

$dateCompare = new DateTime($row['date']);

What format is the $row's date in?

I'd recommend using

$date = DateTime::createFromFormat('The format your dates are in', $row['date']);

See http://www.php.net/manual/en/function.date.php for possible date formats

eg Ymd would parse 2012-10-28


If you have an older version of PHP, you could try this "low tech" solution by comparing as strings.

// Assuming your mysql is Y-m-d
$dateToday = date('Y-m-d')

do{
    if ($row['date'] > $dateToday){
        echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
    } else {  
        echo '<p>FALSE</p>';
    }
while...

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