我想为我的应用创建一个提醒,但如果我比较两个日期,结果总是“好”,即使条件不是真的。这是index.php
的代码:
<?php
require_once 'app/init.php';
date_default_timezone_set('Europe/Brussels');
$itemsQuery = $db->prepare("
SELECT id, name, done, reminder
FROM items
WHERE user = :user
");
$itemsQuery->execute(array(
':user' => $_SESSION['user_id']
));
$items = $itemsQuery->rowCount() ? $itemsQuery : array();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Scorpio To Do</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Shadows+Into+Light+Two" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
</head>
<body>
<div class="list">
<h1 class="header">Scorpio To Do</h1>
<?php if(!empty($items)): ?>
<ul class="items">
<?php foreach($items as $item): ?>
<li>
<a href="indexAdvanced.php?as=advanced&item=<?php echo $item['id']; ?>"><span class="item<?php echo $item['done'] ? ' done' : '' ?>"><?php echo $item['name']; ?></span></a>
<?php if(!$item['done']): ?>
<a href="mark.php?as=done&item=<?php echo $item['id']; ?>" class="done-button">Done</a>
<?php elseif($item['done']): ?>
<a href="mark.php?as=notdone&item=<?php echo $item['id']; ?>" class="done-button">Not Done</a>
<a href="mark.php?as=del&item=<?php echo $item['id']; ?>" class="done-button">Delete</a>
<?php endif; ?>
</li>
<!--/*it's all about this code here*/-->
<a href="#" name="something" id="something">
<?php
echo $datum = $item['reminder']; //echoes good
echo " - ";
$nu = new DateTime('NOW');
echo $nu->format('Y-m-d H:i:s'); //echoes good
echo " - ";
if(strtotime($datum) >= $nu){ //comes out wrong
echo 'ok';
} else{
echo 'nok';
}
?>
</a>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>You havn't added any items yet!</p>
<?php endif; ?>
<form class="item-add" action="add.php" method="post">
<input type="text" name="name" placeholder="Type something here" class="input" autocomplete="off" required>
<input type="submit" value="Add" class="submit">
</form>
</div>
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/scorpiotodo.js"></script>
</body>
</html>
答案 0 :(得分:2)
条件应该是这样的
# convert the datetime to unix
$str_nu = strtotime($today->format('Y-m-d H:i:s'));
# check two unix timestamp
if(strtotime($datum) >= $str_nu){ //comes out wrong
echo 'ok';
} else{
echo 'nok';
}
这是一个链接
Why can't I access DateTime->date in PHP's DateTime class? Is it a bug?
答案 1 :(得分:0)
您正在将格式化日期与时间戳进行比较,但这不起作用。
尝试将$nu
变量替换为time()
:
if(strtotime($datum) >= time()){
答案 2 :(得分:0)
那是因为您正在将对象(DateTime
)与时间戳进行比较。
首先使用getTimestamp()
。
if(strtotime($datum) >= $nu->getTimestamp()) {