View Full Version : How to compare dates in an IF statement
Could someone please explain to me why this code did not work?
if($SQL_Pick_Date > '2010-8-31'){
$Fac_Fee = $Fac_Fee + 3.50;
}
I fixed it by using the code below, but it makes no sense to me why the ">" sign did not work above and why the "<" seems to work here. What gives???
$startdate = "2010-9-1";
if($SQL_Pick_Date < $startdate){
$Fac_Fee = $row['fac_fee'];
} else {
$Fac_Fee = $Fac_Fee + 3.50;
}
With the top code, it adds 3.50 no matter what the date is. Are you supposed to modify the ">" , maybe ">>" as you do with "=="?
Baffled.
fileserverdirect
07-04-2010, 10:08 PM
A date like that is not an interger so it cannot be compared via an inequality statement, try using strtotime() and convert each date with that. Such As:
$startdate = strtotime("2010-9-1");
$SQL_Pick_Date = strtotime($SQL_Pick_Date);
if($SQL_Pick_Date < $startdate){
$Fac_Fee = $row['fac_fee'];
} else {
$Fac_Fee = $Fac_Fee + 3.50;
}
*Untested, but common sense says this should work.
That makes sense. So the '2010-8-31' is interpreted as a string? Yikes, I think I have done date comparisons in other code that maybe isn't working properly either but I thought it was.
So it seems SQL can work with dates like 2010-8-31 but not php? I wonder why they don't fix that.
Thanks very much. Happy 4th!
fileserverdirect
07-04-2010, 10:43 PM
Glad I could help; the reason it's interpretated as a string is because php knows that 123 is less than 234 because simple math says so, but 2010-9-1 according to simple math is 2000 which when compared to say 2010-10-1 would be 1999 which is LESS than 2000 so it would fail, whereas we all know 2010-10-1 is greater than 2010-10-1. The reason php doesn't know this and SQL does is that the timestamp feild or whatever can be formated that way. there is NO way to know that $date is a date because there isn't any attributes to define it, which is why strtotime was invented, to tell you that "This string is a date\time" and it will beconverted into seconds from 1970 January 1, 00:00 UTC, which is a comparable interger.
:) Hope this helps!
Brilliant! Now I get it! Duh! Working with dates has always been a bit of a mystery to me but it's as if a light just went on. Thank you so much for taking the time to explain it that way. SQL has the benefit of the datatype of the field to help identify the data whereas once the data is separated from the table there is no way for php to tell what it is. I always wondered why people seemed to complicate their code with all that strtotime stuff, but now I see why. Mahalo plenty!!! :)
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.