0

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'"

Steve
  • 213,761
  • 22
  • 232
  • 286
user3661657
  • 183
  • 2
  • 2
  • 7
  • 1
    Do you realize that this calc is very imprecise? What if you need to count the months between 13 August 2014 and 1 September 2014? Its 1 month difference or just 18 days? – Steve Aug 13 '14 at 16:08
  • This is really two questions: 1) How to find the month difference between two dates and 2) how to convert a yyyymmdd int to a Date. – Brian Aug 13 '14 at 17:18

3 Answers3

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0
    Int32 beginDate = 20130307;
    Int32 endDate = 20140507;
    Int32 year1 = beginDate / 10000;
    Int32 year2 = endDate / 10000;

    Int32 month1 = (beginDate % 10000) / 100;
    Int32 month2 = (endDate % 10000) / 100;

    Int32 MonthDiff = (12 * year1 + month1) - (12 * year2 + month2);
Bart van der Drift
  • 1,287
  • 12
  • 30
0

If you do not need fractional parts, try something like this:

int beginDate = 20130307;
int endDate = 20140507;

int diff = ((endDate - beginDate)  / 100);

int diff_month = (diff / 100) * 12 + diff % 100;
oppox
  • 1
  • 2