Page 1 of 1

substract one date from another

Posted: Wed Dec 16, 2009 4:53 am
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";
 

Re: substract one date from another

Posted: Wed Dec 16, 2009 4:58 am
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.

Re: substract one date from another

Posted: Wed Dec 16, 2009 11:43 am
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)));