substract one date from another

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
User avatar
dheeraj
Forum Commoner
Posts: 40
Joined: Fri Feb 06, 2009 11:54 am

substract one date from another

Post by dheeraj »

hello guys i m really in a big trouble please help me...
i have two date dates i want to compare both with each other....

i m trying the following code, don't know wht's wrong in this:

Code: Select all

 
$date1 = "15/12/2009";
$date2 = "20/12/2009";
 
$dt1 = date("Y/m/d", strtotime($date1));
$dt2 = date("Y/m/d", strtotime($date2));
 
$cdt1 = strtotime($dt1);
$cdt2 = strtotime($dt2);
 
if($cdt1 > $cdt2)
   echo "1st date is greater";
else
   echo "2nd date is greater";
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: substract one date from another

Post by requinix »

strtotime can't handle DD/MM/YYYY format strings. Split it into year/month/day parts yourself and recombine them into YYYY?MM?DD (the ? can be anything).

Then a regular string comparison will work.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: substract one date from another

Post by AbraCadaver »

tasairis wrote:strtotime can't handle DD/MM/YYYY format strings. Split it into year/month/day parts yourself and recombine them into YYYY?MM?DD (the ? can be anything).

Then a regular string comparison will work.
Correct, but it can handle DD-MM-YYYY:

Code: Select all

$dt1 = date("Y/m/d", strtotime(str_replace('/', '-', $date1)));
$dt2 = date("Y/m/d", strtotime(str_replace('/', '-', $date2)));
Or, unless you need the Y/m/d format, just skip it:

Code: Select all

$cdt1 = strtotime(str_replace('/', '-', $date1));
$cdt2 = strtotime(str_replace('/', '-', $date2));
Or skip the timestamp like tasairis stated and just use the string format:

Code: Select all

$cdt1 = date("Y/m/d", strtotime(str_replace('/', '-', $date1)));
$cdt2 = date("Y/m/d", strtotime(str_replace('/', '-', $date2)));
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply