如何获得下个月的每一天的名字?

时间:2012-07-02 06:46:09

标签: c# winforms datetime

DateTime dt = new DateTime();
dt = DateTime.Now.AddMonths(1);
int x = DateTime.DaysInMonth(dt.Year, dt.Month);
MessageBox.Show(x.ToString());  // works ok - 31

我怎么说以下内容:

foreach (day in dt.Days)
{
string abc = dt.DayOfWeek.ToString();
MessageBox.Show(abc)
}

问题出在第一行 - foreach ......

5 个答案:

答案 0 :(得分:4)

您还可以利用Enumerable.Range和LINQ(以及DaysOfWeek枚举)

DateTime dt = DateTime.Now.AddMonths(1);

Enumerable.Range(1, DateTime.DaysInMonth(dt.Year, dt.Month))
    .Select(dayNumber => new DateTime(dt.Year, dt.Month, dayNumber))
    .Select(dayName => dayName.DayOfWeek.ToString()).ToList()
    .ForEach(day => MessageBox.Show(day));

两个.Select()可以合并,但为了便于阅读,我将它们分开。

答案 1 :(得分:4)

你可以这样做:

DateTime dt = new DateTime();
dt = DateTime.Now.AddMonths(1);
DateTime conditionDateTime = new DateTime(dt.Year, dt.Month,DateTime.DaysInMonth(dt.Year, dt.Month));

 for (DateTime dt1 = new DateTime(dt.Year, dt.Month, 1); dt1 <conditionDateTime; dt1 = dt1.AddDays(1))
     {
        Console.Write(dt1.ToShortDateString() + " : ");
        Console.WriteLine(dt1.DayOfWeek);
     }

这会给你

8/1/2012 : Wednesday
8/2/2012 : Thursday
8/3/2012 : Friday
8/4/2012 : Saturday
8/5/2012 : Sunday
8/6/2012 : Monday
8/7/2012 : Tuesday
8/8/2012 : Wednesday
8/9/2012 : Thursday
8/10/2012 : Friday
8/11/2012 : Saturday
8/12/2012 : Sunday
8/13/2012 : Monday
8/14/2012 : Tuesday
8/15/2012 : Wednesday
8/16/2012 : Thursday
8/17/2012 : Friday
......

答案 2 :(得分:4)

这应该可以胜任。

DateTime Base = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
int x = DateTime.DaysInMonth(Base.Year, Base.Month);
while (Base.Day != x)
{
    Console.WriteLine(Base.DayOfWeek.ToString());
    Base = Base.AddDays(1);
}

答案 3 :(得分:1)

尝试DateTime.ToString(format)方法。

DateTime dt = new DateTime();
String dayName=dt.ToString("ddd");

答案 4 :(得分:1)

试试这个

string day = DateTime.Now.ToString("ddd");