1

I used the following code to find out the time past between two dates:

$date1 = "1900-00-00";
$date2 = "2000-00-00";

$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 daysn", $years, $months, $days);

But this prints 100 years, 0 months, 24 daysn, instead of 100 years, 0 months, 0 daysn

What is going on?

Black
  • 18,150
  • 39
  • 158
  • 271
  • 3
    There's leap-year which add a day a year (every four years, so theres floor(99 / 4) leap days, which is your 24 days - 99 because 1900 and 2000 do not count as leap years), and there's also leap-seconds. You should not try to calculate it on your own. Use the `diff` method as the answer suggests. – vstm Jun 23 '18 at 12:17

2 Answers2

3

You can use the DateTime::diff method of the DateTime class to get the difference between two dates. You don't need to calculate the difference yourself:

<?php
$date1 = "1900-00-00";
$date2 = "2000-00-00";

$dt1 = new DateTime($date1);
$dt2 = new DateTime($date2);

$diff = $dt1->diff($dt2);

printf("%d years, %d months, %d days", $diff->y, $diff->m, $diff->d);
//output: 100 years, 0 months, 0 days

You can also use the procedural style to get and output the difference in two lines:

$diff = date_diff(new DateTime("1900-00-00"), new DateTime("2000-00-00"));
printf("%d years, %d months, %d days", $diff->y, $diff->m, $diff->d);
//output: 100 years, 0 months, 0 days

demo: https://ideone.com/rosaJJ

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
0

Here is the easiest solution :-

$date1 = "1900-00-00";
$date2 = "2000-00-00";

$expDate =  date_create($date2);
$todayDate = date_create($date1);
$diff = date_diff($todayDate, $expDate);
printf("%d years, %d months, %d days", $diff->y, $diff->m, $diff->d);

You will get your expected result .

PHP Web
  • 257
  • 3
  • 8