how to compare between two dates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
davidklonski
Forum Contributor
Posts: 128
Joined: Mon Mar 22, 2004 4:55 pm

how to compare between two dates

Post by davidklonski »

Hi

I have two date strings thata were generated using:

Code: Select all

$date1= date("Y-m-d");
$date2= date("Y-m-d");
Assuming that I am know looking at $date1 & $date2, how can I compare between them?
That is:
return >0 if $date1 comes before $date2
return <0 if $date1 comes after $date2
return 0 if $date1 is exactly the same date as $date2

thanks in advance
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

When comparing dates you should convert them to time stamps
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I wholeheartedly agree with ~phenom. Timestamps makes manipulating dates much easier. However, what you want to do should work with a simple if/else if/else if construct

Code: Select all

if($date1 < $date2)
{
   $retval = 1;
}
else if($date1 > $date2)
{
   $retval = -1;
}
else if($date1 === $date2)
{
   $retval = 0;
}

return($retval);
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply