How to get the selected date of a MonthCalendar control in C#

Viewed 121403

How to get the selected date of a MonthCalendar control in C# (Window forms)

6 Answers

Using SelectionRange you will get the Start and End date.

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
    var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}

If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.

// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;

It'll be helpful if you want just to convert it by:

String myCalendar = monthCalendar1.SelectionRange.Start.ToShortDateString() 

But if you want to get a formatted output you could instead:

String myCalendar = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd")

It's important to use year and day as lower caps, and month as upper or else it'll return you a wrong format, for example, if you do:

String myCalendar = monthCalendar1.SelectionRange.Start.ToString("YYYY-MM-DD")

it will return: YYYY-07-DD (If the original date's month was July)

Related