Comparing dates 'YYYY-MM-DD' > 'YYYY-MM-DD'

Hi,

This feels like a stupid question and im sure ive used it before - I just want to know if i compare dates like this ‘yyyy-mm-dd’ > ‘yyyy-mm-dd’ will it always return the right result. Sorry i know this may sound stupid.

Ive done some testing and it always seems to return the right result but when i searched google for comparing dates no one seem to do it that way and it was all strtotime so i assumed that there must be something wrong with doing it the ‘Y-m-d’ way. If someone could just let me know if i can do it this way then i would be grateful.

Thanks

It SHOULD work correctly - comparison tests on strings (Which these are. PHP doesnt know the difference between a string and a date.) are done character-to-character, left to right. 2 = 2, 0 = 0, 1>0, therefore string 1 > string 2.

IF your strings are guaranteed to be in the format YYYY-MM-DD, there wont be a problem.
If it was YYYY-DD-MM or DD/MM/YYYY or MM/DD/YYYY, you’d have problems.

(Just for example’s sake…)
YYYY-DD-MM
Str1 = ‘2010-30-01’, Str2 = ‘2010-05-02’. Str1 > Str2.

DD/MM/YYYY
Str1 = ‘30/01/2010’ , Str2 = ‘05/02/2010’. Str1 > Str2.

MM/DD/YYYY
Str1 = ‘12/05/2009’, Str2 = ‘01/05/2010’. Str1 > Str2.

Hi,

Thanks for the quick response. I will do it as you have described but could you or someone tell me why i shouldn’t do it as:

if($date1 > $date2){
//do this
} else {
//do that
}

On all my testing it has worked okay - Just wanted to know when doing this could go wrong. I know the format of the timestamps is always going to be the same and i just wondered if i did it this at what point would i run into problems. By this i mean does comparing these under certain conditions return the wrong result.

Thanks again though for quick response

To check if the given date is valid/correct format or not you can use checkdate(). But to compare two dates it is better to convert those date to seconds and compare.


$date1 = '2010-01-01';
$date2 = '2009-01-01';
if(strtotime($date1) > strtotime($date2)){

}
else{

}

Thanks for that - exactly what i was looking for - I will use the strtotime to do them as can see why that would be best practice but wanted to understand why that would be best practice - The dates are created from a form and the formatted the same way everytime. Thanks for the pointer on before BCE as well as im not using those dates but is good to know for the future

Thanks for all the help - I love these forums. :slight_smile:

Slight addition: I’m assuming you’re not going to be using dates that cross the 0 line. If you’re going to use BCE dates, you need a different comparison.