date - PHP DateTime() function not working properly
Get the solution ↓↓↓Solution:
Try to change your
$now = new DateTime("Asia/Kolkata");
to:
$now = new DateTime(null, new DateTimeZone('Asia/Kolkata'));
Answer
Solution:
You need to compare them as objects.. Try something like this..
$now = new DateTime("Asia/Kolkata");
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
I'm not sure if your timezones are set properly on your server but to be sure you could do one of the following as well..
$now = new DateTime('Asia/Kolkata');
if (new DateTime($last_updated, new DateTimeZone('Asia/Kolkata')) > $now) {
echo "exceeded";
}
Or probably even better..
date_default_timezone_set('Asia/Kolkata');
$now = new DateTime('now');
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
Answer
Solution:
Your issue is that since you are not keeping the time in the database and when you compare the date with now which includes the time, the now will always be greater than the date you pull from the database.
The database time 2017-03-17 becomes 2017-03-17 00:00:00 php time.
When you generate php now time it will be 2017-03-17 xx:xx:xx which will always be greater than database time
$last_updated = new DateTime($row["last_updated_date"],new DateTimeZone("Asia/Kolkata"));
$today = new DateTime('now',new DateTimeZone("Asia/Kolkata")); //gets current date time
$today->setTime(0,0); // back to the beginning of the day
//echo $last_updated->getTimestamp . | . $today->getTimestamp; // for debugging purpose
if(($last_updated->getTimestamp >= $today->getTimestamp)) {
// note that I have used '>=' to allow the current date
}
You can also use the DateTime->diff() function.
Reference: http://php.net/manual/en/class.datetime.php
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non well formed numeric value encountered
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.