获取所选月份和年份的第一天和最后一天?

时间:2017-05-29 07:13:22

标签: c# datetime

我的WinForm上有2个ComboBox。

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

如果我选择2017年1月和2017年它应该显示如下:

1-wednesday
2-Thursday
.
.
.
直到那个月的最后一天

2 个答案:

答案 0 :(得分:1)

你可以这样做:

//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"));
}
编辑:我忘记了DateTime.DaysInMonth,它可以用于更简单的解决方案:

//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"));
}

答案 1 :(得分:0)

DateTime结构只存储一个值,而不存储值范围。 MinValueMaxValue是静态字段,其中包含DateTime结构实例的可能值范围。这些字段是静态的,与DateTime的特定实例无关。它们与DateTime类型本身有关。

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

参考here