How 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]
How 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]
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);