Months between two integer dates

I have 2 dates as integers. How can i find the month difference between these two integers in c#?

For example:

Int32 beginDate= 20130307(yyyymmdd)
Int32 beginDate= 20140507(yyyymmdd)

I need the result as 14 months.

I have already tried:

DateTime beginDatepar = Convert.ToDateTime(beginDate);
DateTime endDatepar = Convert.ToDateTime(beginDate);
int monthDifference = ((beginDatepar.Year - endDatepar.Year) * 12) + 
                        beginDatepar.Month - endDatepar.Month;

But when I am converting Int32 to Datetime the error is "Invalid cast from 'Int32' to 'DateTime'"

Jon Skeet
people
quotationmark

You can use my Noda Time library for that. It was created specifically to make things like this simpler.

// TODO: Encapsulate this conversion in a separate method
LocalDate start = new LocalDate(beginDate / 10000,
                                (beginDate / 100) % 100,
                                beginDate % 100);
LocalDate end = new LocalDate(endDate / 10000,
                              (endDate / 100) % 100,
                              endDate % 100);

Period period = Period.Between(start, end, PeriodUnits.Months);
int months = period.Months;

Note that this will return the complete months - so if you add months to start, you'll get a value before or equal to end, but if you add months + 1 it will be strictly after end.

So for example, May 20th to July 10th would count as one month, not two.

As a separate matter, I'd strongly advise you to stop representing dates as integers like this in the first place. Trace back to where the code first does this, and fix it.

people

See more on this question at Stackoverflow