简体   繁体   English

为什么DateTime :: sub无法按预期工作?

[英]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. 由于这个问题的答案,我已经设法仅使用MySQL从MySQL数据库中输出将来(即今天之后)的列表日期。 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): 我尝试使用以下代码使用DateTime::sub ,但是它杀死了我的脚本(我只是得到一个空白屏幕-如果我注释掉DateTime :: sub行,它将再次起作用。我仍然没有解决如何获取PDO来回显错误详细信息):

$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? $ row的日期采用什么格式?

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 有关可能的日期格式,请参见http://www.php.net/manual/zh/function.date.php

eg Ymd would parse 2012-10-28 例如Ymd会解析2012-10-28


If you have an older version of PHP, you could try this "low tech" solution by comparing as strings. 如果您有旧版本的PHP,则可以通过比较字符串来尝试这种“低技术含量”解决方案。

// 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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM