-3

I have 2 ComboBoxes on my WinForm.

combobox1 --> displaying months
combobox2 --> displaying  years

If I select January And 2017 It should display me something like:

1-wednesday
2-Thursday
.
.
.

till last of that month

Samurai Jack
  • 2,985
  • 8
  • 35
  • 58
  • 7
    Try something on your own first. Hint: use DateTime.DaysInMonth – Alkis Giamalis May 29 '17 at 07:14
  • First try and place your code where ever you got struggle then anyone can help you – Shakir Ahamed May 29 '17 at 07:16
  • If you are talking about this DateTime date = new DateTime(); var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month); Console.WriteLine(lastDayOfMonth); but it returns 31 .. I want to know about the day on 31st? – jahanzaib ijaz May 29 '17 at 07:17

2 Answers2

1

you can do it like this:

//clear items
comboBox1.Items.Clear();

int month = 5;
int year = 2017;

//new datetime with specified year and month
DateTime startDate = new DateTime(year, month, 1);

//from first day of this month until first day of next month
for (int i = 0; i < (startDate.AddMonths(1) - startDate).Days; i++)
{
    //add one day to start date and add that in "number - short day name" in combobox
    this.comboBox1.Items.Add(startDate.AddDays(i).ToString("dd - ddd"));
}

EDIT: I forgot about DateTime.DaysInMonth, which can be used for even simplier solution:

//clear items
comboBox1.Items.Clear();

int month = 5;
int year = 2017;
//calculate how many days are in specified month
int daysInMonth = DateTime.DaysInMonth(year, month);

//loop through all days in month
for (int i = 1; i <= daysInMonth; i++)
{
    //add one day to start date and add that in "number - short day name" in combobox
    this.comboBox1.Items.Add(new DateTime(year, month, i).ToString("dd - ddd"));
}
Nino
  • 6,931
  • 2
  • 27
  • 42
0

DateTime structure stores only one value, not range of values. MinValue and MaxValue are static fields, which hold range of possible values for instances of DateTime structure. These fields are static and does not relate to particular instance of DateTime. They relate to DateTime type itself.

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

reference here

Elis
  • 91
  • 1
  • 4