3

I was trying to find the number of months between two dates using date_diff() in PHP. As we all know the number of months between 2019-03-01 and 2020-01-31 is 11 months, but the following code return 10 months.

$date1=date_create("2019-03-01");
$date2=date_create("2020-01-31");
$diff=date_diff($date1,$date2);
echo $diff->format("%m months");

Output

10 months

Why this code return 1 month less?

5
  • 1
    Likely because the actual duration is 10 months and 30 days, but you're only displaying the "month" portion. echo $diff->format("%m months %d days"); Commented Feb 26, 2020 at 19:15
  • but why it return like this? Commented Feb 26, 2020 at 19:17
  • Because it's not a full 11 months. Commented Feb 26, 2020 at 19:17
  • 2020-01-31 is treated as 2020-01-31 00:00:00 and 2019-03-01 as 2019-03-01 00:00:00 . is this the reason? Commented Feb 26, 2020 at 19:18
  • That's correct. Commented Feb 26, 2020 at 19:27

2 Answers 2

3

If you need the difference in months from the beginning of the first day to the end of the last day at midnight, you can also set the end date to midnight (24h !) or add a day.

<?php
$dateStart = date_create("2019-03-01");
$dateEnd = date_create("2020-01-31");

//set Time to midnight or add a day
$dateEnd->setTime(24,0,0);

$diff = date_diff($dateStart,$dateEnd);
echo $diff->format("%m months");
//11 months

try self.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! I was trying to get days difference and using date('now') vs a set date and did not realise at first the amount of hours was changing the day value, makes sense! I used "new DateTime('now')->setTime(0, 0)"
2

The difference is 10 months and 30 days, which is what date_diff() returns:

object(DateInterval)#3 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(10)
  ["d"]=>
  int(30)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(336)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

ETA as @showdev commented above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.