0

I have this dates here:

date1 = 2015-1-1
date2 = 2014-1-1

When I use this code:

int difference = date1.Value.Month - date2.Value.Month

This returns 0. I want the actual result to be 12 months since the date difference is within a year.

Someone help out? Completely new to this.

Break the Law
  • 217
  • 2
  • 14
  • Are `date1` and `date2` DateTime objects? [Check this](http://stackoverflow.com/a/4639057/3846058) – Inspector Squirrel Feb 25 '15 at 10:17
  • 1
    possible duplicate of [Difference in months between two dates](http://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) –  Feb 25 '15 at 10:17
  • Its correct because value of `date1.Value.Month is 1` and date2.value.Month is again 1 so 1-1 is 0 :-) – Mox Shah Feb 25 '15 at 10:18
  • This link will be help you so so much. [Click here][1] [1]: http://stackoverflow.com/questions/4638993/difference-in-months- – Shahzad Khan Feb 25 '15 at 12:46

4 Answers4

0

Try this code

DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
Console.WriteLine((date1.Month - date2.Month) + 12 * (date1.Year - date2.Year));
Mox Shah
  • 2,967
  • 2
  • 26
  • 42
0
var difference = date1.Value.Ticks - date2.Value.Ticks;
var dateDifference = new DateTime(difference);
int numberOfMonths = (dateDifference.Years * 12) + dateDifference.Months;
ediblecode
  • 11,701
  • 19
  • 68
  • 116
0

You can't get the exact result since day/years can change but you still can try this:

 //you can determine that the average month has 30.44 days (source:google)
const double daysToMonths = 30.4368499;
     DateTime date1 = Convert.ToDateTime("2015-1-1");
     DateTime date2 = Convert.ToDateTime("2014-1-1");
//round is optional here
     Double Diff = Math.Round(date1.Subtract(date2).TotalDays/daysToMonths,0);
Emmanuel M.
  • 441
  • 6
  • 11
-1

I resolved this issue by adding Microsoft.VisualBasic in my reference and by using the DateDiff function from Visual Basic. By using this, I don't need to manually compute the date anymore, I just set the interval and the 2 dates then it executes perfectly.

DateAndTime.DateDiff(DateInterval.Month, (DateTime)promoevent.TargetStartDate, (DateTime)promoevent.TargetEndDate);
Break the Law
  • 217
  • 2
  • 14