-2

enter image description hereHow to find Number of months between two selected dates from month Calendar control in c# windows ? Than I want to populate text box 'Total Month' with that data. I attached the screen shot below.

[![Windows Form][1]][1]
  • SO is not for requesting general "how tos" that you can find with a simple Google search. You won't get much assistance here until you post your code, tell us what undesired behavior you're getting from it, and what steps you've taken to fix it. Please read [how to ask a good question.](https://stackoverflow.com/help/how-to-ask) Also, this looks like a school homework assignment, and [we won't just do your homework for you](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). – CDove Feb 19 '18 at 12:52
  • Possible duplicate of [Difference in months between two dates](https://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) – Francesco B. Feb 19 '18 at 14:22

1 Answers1

1

Your question is a little vague, so don't be surprised if the answer is a little in accurate for your needs.

Your first challenge here, before you can get the amount of months between two dates, is that you need to get the two dates to start with.

In a C# Winforms application, you can double click on the Calendar control in order for Visual Studio to generate an onDateChanged event handler.

Perform the double click for each of your calendar controls and something like this in:

        private DateTime startDate;
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            startDate = dateTimePicker1.Value;
        }

        private DateTime endDate;
        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            endDate = dateTimePicker2.Value;
        }

Now once you have your two dates, the complicated bit arises with the actual calculation of months between two points. Simple TimeSpan objects do not provide access to a TotalMonths method, although, if you wanted to, you could write such an extension method.

Various StackOverflow pages deal with the calculation of Total Months between given DateTimes. Use the above code to get your two dates, then use the code on the following pages to perform the calculations.

How can I calculate the numbers of month between two dates in C#

calculating the difference in months between two dates

I particularly like this solution:

        public static int MonthDifference(this DateTime lValue, DateTime rValue)
        {
            return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));
        }

You should be able to perform

int totalMonths = date1.MonthDifference(date2);
Baaleos
  • 1,703
  • 12
  • 22