Compare current date as Y-m-d against Y-m-d string which doesn't have zero padded days
Asked Answered
L

13

161

How can I compare two dates in PHP?

The date is stored in the database in the following format

2011-10-2

If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?

I tried this,

$today = date("Y-m-d");
$expire = $row->expireDate //from db

if($today < $expireDate) { /*do something;*/ }

but it doesn't really work that way. What's another way of doing it?

Lab answered 2/10, 2010 at 22:19 Comment(1)
Assign the db dates to a DateTime object and then compare those objects. You can find a nice example in #961574Laird
T
89

in the database the date looks like this 2011-10-2

Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.

Tautomer answered 2/10, 2010 at 22:31 Comment(3)
but what if they look like this, 2011-10-02 and 2012-02-10, for month comparison 1 > 0, but 2011-10-02 < 2012-02-10Monahon
@Davo, the comparison stops at the first character that is different. In this case, the fourth digit of '1' < '2', so you get the result you expect.Tautomer
will the following work 2016-03-27 11:59:47 ::: 2016-03-14 10:30:00?Cupule
M
259

If all your dates are posterior to the 1st of January of 1970, you could use something like:

$today = date("Y-m-d");
$expire = $row->expireDate; //from database

$today_time = strtotime($today);
$expire_time = strtotime($expire);

if ($expire_time < $today_time) { /* do Something */ }

If you are using PHP 5 >= 5.2.0, you could use the DateTime class:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

Or something along these lines.

Mingle answered 2/10, 2010 at 22:25 Comment(5)
If I recall correctly, the concern about 1st of January of 1970 only applies to old versions of PHP running on Windows and it was never an issue on Unix.Hawaiian
Wouldn't it now be "If all your dates are posterior to the 1st of January of 1970" and "previous to 2038"? watch our for the y2k38 bug. strtotime will return false for larger dates. #2013089Nathalienathan
Note that the DateTime method is the preferred method. That object can do far more than strtotime ever could.Aldaaldan
new DateTime('now') also works to retrieve today's dateTris
@Tris Just use new DateTime(), which is the same thing. Also, in the case of bad user input, the constructor can throw an Exception, so make sure that is handled.Tutelage
T
89

in the database the date looks like this 2011-10-2

Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.

Tautomer answered 2/10, 2010 at 22:31 Comment(3)
but what if they look like this, 2011-10-02 and 2012-02-10, for month comparison 1 > 0, but 2011-10-02 < 2012-02-10Monahon
@Davo, the comparison stops at the first character that is different. In this case, the fourth digit of '1' < '2', so you get the result you expect.Tautomer
will the following work 2016-03-27 11:59:47 ::: 2016-03-14 10:30:00?Cupule
B
29

Just to compliment the already given answers, see the following example:

$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database



if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) { 
    //do something; 
}

Update: Or simple use old-school date() function:

if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
    //echo not yet expired! 
}   
Brogan answered 1/10, 2013 at 12:27 Comment(2)
Date is a function, not a class/constructor.Dressingdown
@Dressingdown thanks for the comment, I changed the Capital letter to remove possible confusion.Brogan
M
10

I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types

SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
Meshwork answered 3/10, 2010 at 0:25 Comment(2)
thanks but i actually use date() i dont store todays date in a dbLab
But you store expireDate in a db. Compare this date with NOW()Meshwork
A
7
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db 
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);

//echo $timeDiff;
if($diff->days >= 30){
    echo "Expired.";
}else{
    echo "Not expired.";
}
Amundson answered 18/8, 2016 at 7:11 Comment(0)
G
2

You can convert the dates into UNIX timestamps and compare the difference between them in seconds.

$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
   {
     echo "Enter a valid date";
   }
Glycol answered 5/12, 2014 at 3:21 Comment(0)
L
2

Here's a way on how to get the difference between two dates in minutes.

// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;
Levesque answered 6/12, 2017 at 12:43 Comment(3)
The question is asking for comparing 2 dates - your answer is adding a load of extra stuff (i.e. setting online/offline status) which isn't necessary as an answer to the question. The part of your answer where the comparison takes places is virtually the same as the already existing answer here.Opia
Updated the question, i posted the wrong answer in the wrong question ^^ ;) It's not the same as the answer, just adding my input on how to compare them and get the difference in minutes.Levesque
I've removed my downvote because of your update, looks much better now :)Opia
H
0

I had that problem too and I solve it by:

$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db

if(($today - $expire) > $NUMBER_OF_DAYS) 
{ 
    //do something; 
}
Hydrosol answered 8/4, 2014 at 7:26 Comment(2)
Why this technique works should be explained in the answer.Edisonedit
Please answer the OP's posted question, not how you solved your own unique scenario.Edisonedit
B
0

Found the answer on a blog and it's as simple as:

strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400

And you'll get the days between the 2 dates.

Braziel answered 20/12, 2015 at 9:29 Comment(1)
This appears to be solving a different problem. Please only answer the question asked by the OP.Edisonedit
P
0

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {/* do something */} 
if ($startdate > $date) {/* do something */}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

Phyla answered 3/10, 2016 at 11:45 Comment(3)
d-m-Y will not work.. Y-m-d (with leading zero like 2016-05-08) will work. Check those dates in d-m-Y format 01-10-2016 and 20-02-2016, comparing as strings 0 < 2, it will stops comparing but incorrectly...Swick
Here is proof that your technique will fail to correctly compare the OP's dates against today's date: 3v4l.org/SNHKTEdisonedit
The OP has a different date format. the date looks like 2011-10-2.Edisonedit
I
0

Here's my spin on how to get the difference in days between two dates with PHP. Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.

$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Infinitesimal answered 10/1, 2019 at 15:12 Comment(0)
P
0

If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:

$date = $row->expireDate;

$date->add(new DateInterval('PT24H')); // adds 24 hours

$now = new \DateTime();

if($now < $date) { /* expired after 24 hours */ }

But in your case you could do the comparison just as the following:

$today = new DateTime('Y-m-d');

$date = $row->expireDate;

if($today < $date) { /* do something */ }
Pirate answered 12/6, 2020 at 9:26 Comment(9)
This answer is ignoring the originally posted question. Please use the sample data provided by the OP.Edisonedit
It is not exactly what the guy is asking for help but I thought this way could help if one understands the principles.Pirate
I understand the principles, but this code does not answer the question asked. This page is already bloated with incorrect and unrelated answers -- this only confuses researchers and wastes their time. I am trying to look out for researchers.Edisonedit
Well I think it's not that difficult, he could've used the DateTime() class instead of the date() function. The answer I put above is in somehow to give ideas to the researchers.Pirate
Multiple answers on this page were already advising the use of a datetime object. I don't feel that your answer is adding any new value to this page for researchers. This is why I downvoted and voted to delete this answer.Edisonedit
The ones above are really confusing. Reason why I have proposed a simpler way and the code is very readable, isn't it ?Pirate
I am going to stop repeating myself and disengage ftom this discussion. The 2nd highest solution (https://mcmap.net/q/150006/-compare-current-date-as-y-m-d-against-y-m-d-string-which-doesn-39-t-have-zero-padded-days) shows a dreadfully simple (unbeatable) way of creating two datetime objects. I have absolutely no idea what your magical requestDate() method does -- there is no mention of it anywhere. I would not use your answer, nor recommend that any researcher use your solution. I do not foresee myself changing my vote.Edisonedit
You're right about the requestDate() method but you should've told me earlier, don't you think ? But anyway I got it.Pirate
It is NOT my responsibility to babysit your answer. You need to test your code before posting it in Stack Overflow. Not testing your broken code will mean researchers will waste their time. Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (Y-m-d) at position 1 (-): Unexpected characterEdisonedit
G
-1

first of all, try to give the format you want to the current date time of your server:

  1. Obtain current date time

    $current_date = getdate();
    
  2. Separate date and time to manage them as you wish:

    $current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
    $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
    
  3. Compare it depending if you are using donly date or datetime in your DB:

    $today = $current_date_only.' '.$current_time_only;
    

    or

    $today = $current_date_only;
    
    if($today < $expireDate)
    

hope it helps

Goggles answered 1/5, 2018 at 14:12 Comment(1)
This answer makes no attempt to solve the original question. The OP has no interest in hours, minutes, or seconds.Edisonedit

© 2022 - 2024 — McMap. All rights reserved.