-2

I am trying to show the difference in days and months between 2 dates

$date1 = $start;
$date2 = $end;
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

However this shows as 0 years, 0 months, 0 days

The dates in $start and $end are in the format DD/MM/YYYY

Shaun
  • 153
  • 8
  • @Prafulla who is this comment for? – Shaun Sep 30 '15 at 11:56
  • Your input have the wrong format. You should use an other format or `DateTime::createFromFormat`. Using the DateTime object makes your code also easier and you could just use `DateTime::diff()` $d1 = DateTime::createFromFormat("d/m/Y", $date1); $d2 = DateTime::createFromFormat("d/m/Y", $date2); $span = $d1->diff($d2); printf("%d years, %d months, %d days\n", $span->y, $span->m, $span->d); – Philipp Sep 30 '15 at 11:59
  • @shaun, actually i comment for derenir, who deleted his comment – Prafulla Sep 30 '15 at 12:00
  • convert date format `$date1 = DateTime::createFromFormat('d/m/Y', $date11)->format('Y-m-d'); $date2 = DateTime::createFromFormat('d/m/Y', $date12)->format('Y-m-d');` – Prafulla Sep 30 '15 at 12:00
  • Why has this question been downvoted? It isnt a duplicate due to the UK time format? – Shaun Sep 30 '15 at 12:01

1 Answers1

1

As you have stated within your comment that The dates in $start and $end are in the format DD/MM/YYYY. So you need to first replace that into d-m-Y using str_replace or DateTime::createFromFormat so try using like as

$date1 = str_replace('/','-',$start);
$date2 = str_replace('/','-',$end);

PHP date conversion to strtotime

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54