2

I have a question here. I need to get the difference betweeen 2 dates in months by using Yii2. I know that I should use diff and format it in months, but it's not working. Could someone help me to solve the problem?

Here is my line that I need to count the difference in months:

$holidays = 'floor(datediff(curdate(), employment_date))';

Thanks for any help

devorye
  • 193
  • 2
  • 16
  • http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php – Amitesh Kumar Apr 13 '17 at 08:34
  • Is it possible to do it in 1 or 2 lines? I don't want to write 20 lines of code just to do the difference in months – devorye Apr 13 '17 at 08:36
  • I dont think so , there was a extension in yii 1 try to find extension in yii2 , or write it once and use it many times. – Amitesh Kumar Apr 13 '17 at 08:37
  • [You can write four lines?](http://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates) – Insane Skull Apr 13 '17 at 08:59
  • Possible duplicate of [Elegant way to get the count of months between two dates?](http://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates) – wormi4ok Apr 13 '17 at 09:33

2 Answers2

1

There is already an good answer by @Vincent Savard. Here it is in two lines:

$diff = (new DateTime($employment_date))->diff(new DateTime());
$holidays = $diff->m + $diff->y*12;
Community
  • 1
  • 1
wormi4ok
  • 602
  • 7
  • 11
1

Since you are using mysql, you can use TIMESTAMPDIFF:

$holidays = '(TIMESTAMPDIFF(MONTH, employment_date, curdate()))';
topher
  • 14,790
  • 7
  • 54
  • 70