20 October, 2010

Compare dates using PHP

Some times before, one of my friend asked me how to compare two dates using php. As he was a beginner and didnt have much knowledge regarding date and time functions in php, i did some kind of explanation to him.
We can use a php function strtotime in order to compare two dates in php. strtotime converts any date format description to Unix timestamp, and what we can do is convert, dates that are to be compared, to unix timestamp and perform a simple comparision.
Let's assume, we need to check if our registration has expired.

//first take today's date
$todaysDate = date("Y-m-d");

//get the expiration date, mat be from database or somewhere else
$expirationDate = "2010-12-06";

//now we convert both, today's date and expiration date to unix timestamp
$todaysDateStr = strtotime($todaysDate);
$expirationDateStr = strtotime($expirationDate);

//now simply compare the two variables
if($expirationDateStr > $todaysDateStr) {
echo "Your registration is valid!";
else {
echo "Your registration has expired!";

And that's it. The date format can be any like "-" or "/". Just convert it to unix timestamp and then compare the dates using php comparision operators.
I hope this helps someone.

No comments: