试图比较两个日期...一个来自存储为DATE的mysql DB和一个使用DateTime对象的日期

时间:2013-11-01 02:57:25

标签: php mysql sql date datetime

我一直尝试使用if语句比较两个日期然后运行另一个查询并更新mysql数据库失败。我不确定我哪里出错了。如果我使用procedural并使用

date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date30)));

然后我获得了boosterWithinDays列中每个字段的更新。

如果我尝试使用DateTime对象

$boosterDate = new DateTime($row['boosterDate']);
$boosterDate->format("Y-m-d");

然后我根本没有更新。我已经设置了一些boosterDates超过30天,有些更少,似乎没有任何工作。

以下是完整的代码:

    <?php
//date_default_timezone_set('America/Chicago');
$todaysDate = new DateTime('now');
$formattedDate = $todaysDate->format('Y-m-d');
$date = new DateTime ('now');
$date90 = $date->add(new DateInterval('P90D'));
$date90 = $date->format('Y-m-d');
$date = new DateTime ('now');
$date60 = $date->add(new DateInterval('P60D'));
$date60 = $date->format('Y-m-d');
$date = new DateTime ('now');
$date30 = $date->add(new DateInterval('P30D'));
$date30 = $date->format('Y-m-d');
//echo $date90;
//echo "<br />";
//echo $formattedDate;

$sql = "SELECT * FROM service;";

if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');  
}
while($row = $result->fetch_array()){
//Get all the rows and store them in an array
$firstQueryRows[] = $row;
}
foreach($firstQueryRows as $row){
//do a new query with $row
$patientID = $row['patientID'];
$serviceID = $row['serviceID'];
//$boosterDate = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $row['boosterDate'])));
//$date30 = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date30)));
//$date60 = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date60)));
//$date90 = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date90)));
$boosterDate = new DateTime($row['boosterDate']);
//$boosterDate->format("Y-m-d");
//$interval = $boosterDate->diff($date30);
$boosterDate = $boosterDate->format("Y-m-d");
var_dump($boosterDate > $date30);
echo "<br /><br />";
print "This is the booster date" . " " . ($boosterDate) . " ";
echo "<br /><br />";
print "This is todays date plus 30 days" . " " . ($date30) . " ";
if($boosterDate < $date30){
//echo "The date is less than 30" . " " . $row['serviceID'] . "<br /><br />";
//echo $date30 . "<br /><br />";
//echo $boosterDate;
echo "this is being shown because boosterDate object is less than date30 object";
$sql = "UPDATE service SET boosterWithinDays = 30;";
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');  
}
}else{
NULL;
}
}
//$date = $row['boosterDate'];
//$id = $row['patientID'];
//echo $date . " " . $id . "<br /><br />";
//echo date_default_timezone_get();

?>

1 个答案:

答案 0 :(得分:0)

可能是我,但是因为你要比较2个对象(DateTime),使用diff函数并获得反转标志是不是更好?

if ($boosterDate->diff($date30)->invert) {
    // other code    
}