-1

I've a little question. How I can calculate the months between the current month and another given month? For example: now it's February, I want to know, how many months are between February and let's say January. Is there a clean way to do this?

Bob
  • 5,510
  • 9
  • 48
  • 80
Marcel Hoffmann
  • 973
  • 1
  • 8
  • 15
  • Needs clarification: Suppose it's December and you want number of months between that and January. Is the answer 1 or 11? – ChrisV Feb 12 '15 at 10:32
  • Yes there are lots of ways to do this, Did you tried anything ? – Mahesh Feb 12 '15 at 10:32
  • If it's December, the number between January should be 1. – Marcel Hoffmann Feb 12 '15 at 10:35
  • but you can't get this information properly without taking the year into account or making some additional assumptions. If the current month is feburary and the specified one is december, how do you know whether the result should be 2 or 10? – Thomas Lielacher Feb 12 '15 at 10:46
  • Check my pseudo-code answer (since you didn't specify any programming language). difference is: (oy*12 - om) - (cy*12 - cm) where `cy` is the currentYear, `oY` is the other year, `cm` is the currentMonth and `om` is the otherMonth, and `oy > cy` Edit: nevermind, just saw you added c# – IneedHelp Feb 12 '15 at 10:53

1 Answers1

0

Assuming your months are encoded like:

Jan = 1
...
Dec = 12,

the difference will be:

int difference = m2 >= m1 ? m2 - m1 : 12 + m2 - m1;

where m1 - the first month and m2 - the another one.

johnnyjob
  • 380
  • 1
  • 9