Savan
Savan

Reputation: 171

Number of months between given months

I want to find the count of number of months between given months such as Jan,Feb,Mar...

eg - Input - Jun , Aug
Output -3
Input - Dec,Mar
Output - 4

 $string = "Jun";
 $month_number1 = date("n",strtotime($string));
 $string = "Aug";
 $month_number2 = date("n",strtotime($string));
 $monthCount = ($month_number2 - $month_number1) +1 ;

But this doesn't work for Dec and Mar .
Please help.Thank you

Upvotes: 0

Views: 49

Answers (1)

Octopus
Octopus

Reputation: 8325

The secret to cyclic quantities like this is to calc the modulus of your delta by the number of elements, in this case 12, for twelve months. So, basically

(m2 - m1) % 12

But many languages don't do mods on negative numbers very effectively, so add the same number into the difference calc:

n = (12 + m2 - m1) % 12

Upvotes: 2

Related Questions