Reputation: 18629
I am trying to compare today and a given date in PHP, and I am getting some unexpected results.
Here is some output I have:
echo time(); // 1315940430
echo strtotime("+20 days", $date_string); // 1730010
echo $date_string; // 2010-9-30
and when I try something like this:
if (date() > date('Y-m-d', strtotime("+20 days", $date_string)))
{
}
And the check always returns true no matter what the $date_string is. Any idea how to fix this?
Upvotes: 0
Views: 183
Reputation: 31300
If you wanted to play around with the new date functionality, you could also try something like this:
// If $otherday is in the future
if ( (int)date_diff(new DateTime(), new DateTime($otherday))->format("%r%a") > 0 ) {
// ... blah
}
For example:
foreach ( array("1 year", "1 month", "1 week", "1 day", "1 hour") as $adjustment ) {
printf("-/+ $adjustment %d/%d\n",
date_diff(new DateTime(), new DateTime("-$adjustment"))->format("%r%a"),
date_diff(new DateTime(), new DateTime("+$adjustment"))->format("%r%a")
);
}
Output:
-/+ 1 year -365/366
-/+ 1 month -31/30
-/+ 1 week -7/7
-/+ 1 day -1/1
-/+ 1 hour 0/0
See date_diff and DateInterval and DateInterval::format
Upvotes: 0
Reputation: 146302
if (date('Y-m-d') > date('Y-m-d', strtotime("+20 days", $date_string)))
{
}
The reason is because the 2nd part of your if statement is in 1970
!
That's why it always returns true.
See demo: http://codepad.org/tmmuoSXv
Code:
<?php
$date_string = '2010-05-02';
$date_now = date('Y-m-d');
$converted = date('Y-m-d', strtotime("+20 days", $date_string));
echo $date_now.PHP_EOL.$converted.PHP_EOL;
if ($date_now > $converted)
{
echo 'hello'.PHP_EOL;
}
echo 'there'.PHP_EOL;
?>
Output:
2011-09-13
1970-01-21
hello
there
What you to do is this:
$converted = date('Y-m-d', strtotime("+20 days", strtotime($date_string)));
The extra strtotime
fixes it all up for you and you get the correct date :-)
Demo: http://codepad.org/Fhnx5er0
Demo(if is false): http://codepad.org/jsnEMUGI
Upvotes: 2
Reputation: 1185
You want to compare the timestamps:
if (time() > strtotime("+20 days", $date_string))
{
}
Upvotes: 0
Reputation: 99889
date()
takes at least one argument (the format).
Try this:
if (date('U') > strtotime("+20 days", $date_string)) {
The U
format specifier returns the timestamp; just like strtotime(); so you can compare its output directly to the output of strtotime.
This is also a good solution:
if (date_create() > date_create($date_string)->modify('+20 days')) {
Upvotes: 1
Reputation: 8017
Convert both dates to timestamps (date('U')
) and do if ($date1 > $date2)
.
Upvotes: 1