简体   繁体   中英

Comparing dates with PHP

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?

if (date('Y-m-d') > date('Y-m-d', strtotime("+20 days", $date_string))) 
{

}

Update:

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


SOLVED:

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

将两个日期转换为时间戳( date('U') )并执行if ($date1 > $date2)

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')) {

You want to compare the timestamps:

if (time() > strtotime("+20 days", $date_string))
{

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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