查找日历的第一天

时间:2011-02-03 07:33:08

标签: c# datetime calendar

我想要做的是创建一个简单的日历,我想找到特定月份第一周的第一天。我的日历是星期一 - >星期日日历和以下代码有效,但正如你所看到的那样不太好。任何人都可以更好地了解如何在日历中获得第一个日期。

var now = new DateTime(Year, Month, 1);
now = now.AddDays(1-(int)now.DayOfWeek);
now = now.Day > 15 ? now : now.AddDays(-7);

日历最终会如下所示:

| <  |        Jan  2011       |  > |
------------------------------------
| Mo | Tu | We | Th | Fr | Sa | Su |
|[27]| 28 | 29 | 30 | 31 | 01 | 02 |
| 03 | 04 | 05 | 06 | 07 | 08 | 09 |
| .. | .. | .. | .. | .. | .. | .. |
| .. | .. | .. | .. | .. | .. | .. |
| 31 | 01 | 02 | 03 | 04 | 05 | 06 |

在这个“形象”中,这是我试图找到的[27]日期。

解决方案(发现我更好/更清洁循环然后计算):

    public DateTime FirstDay()
    {
        var date = new DateTime(Date.Year, Date.Month, 1);
        while (true)
        {
            if (date.DayOfWeek == DayOfWeek.Monday)
                return date;
            date = date.AddDays(-1);
        }
        return date;
    }

    public DateTime LastDay()
    {
        var date = new DateTime(Date.Year, Date.Month, 
                                DateTime.DaysInMonth(Date.Year, Date.Month));
        while (true)
        {
            if (date.DayOfWeek == DayOfWeek.Sunday)
                return date;
            date = date.AddDays(1);
        }
        return date;
    }

/ BR 安德烈亚斯

7 个答案:

答案 0 :(得分:9)

我会这样做。这很容易理解:

var firstDayOfMonth = new DateTime(year, month, 1);
DateTime startOfCalendar = 
    FirstDayOfWeekOnOrBefore(
        firstDayOfMonth,
        DayOfWeek.Monday
    );

public static DateTime FirstDayOfWeekOnOrBefore(
    DateTime date,
    DayOfWeek dayOfWeek
) {
    while(date.DayOfWeek != dayOfWeek) {
        date = date.AddDays(-1);
    }
    return date;
}

此外,如果您想要将日历更改为星期一以外的其他内容,那么现在就很简单了。使用模运算的解决方案不可维护。

答案 1 :(得分:4)

您可以使用modulo计算没有条件语句的填充天数:

DateTime firstOfMonth=new DateTime(year,month,1);
var weekDay=firstOfMonth.DayOfWeek;
int fillerDays=((int)weekDay+6)%7;
DateTime firstDayInCalendar=firstOfMonth.AddDays(-fillerDays);

答案 2 :(得分:1)

你可以尝试这个假设第一天你指的是星期一

DateTime dt = new DateTime(2011, 2, 2);
Console.WriteLine(dt.AddDays((8 - (int)dt.DayOfWeek) % 7));

答案 3 :(得分:1)

我不喜欢while循环,因为它们与LINQ一起使用时很昂贵 希望其他人可以重复使用此代码:(如果你在美国,那么只需删除[+ 6]%7)]两行)

    /// <summary>
    /// Expands the month.
    /// | <  |        Jan  2011       |  > |
    /// ------------------------------------
    /// | Mo | Tu | We | Th | Fr | Sa | Su |
    /// |[27]| 28 | 29 | 30 | 31 | 01 | 02 |
    /// | 03 | 04 | 05 | 06 | 07 | 08 | 09 |
    /// | .. | .. | .. | .. | .. | .. | .. |
    /// | .. | .. | .. | .. | .. | .. | .. |
    /// | 31 | 01 | 02 | 03 | 04 | 05 | 06 |
    /// </summary>
    /// <param name="start">Some day in the month of interest, the start date is updated to become the date of firstDayInCalendar</param>
    /// <returns>The number of days to show. This value is either (28, 35 or 42)</returns>
    public static int ExpandMonth(ref DateTime start)
    {
        DateTime first = new DateTime(start.Year, start.Month, 1);
        DateTime last = new DateTime(start.Year, start.Month, DateTime.DaysInMonth(start.Year, start.Month));
        start = first.AddDays(-((int)first.DayOfWeek + 6) % 7);
        last = last.AddDays(7 - ((int)last.DayOfWeek + 6) % 7);
        return last.Subtract(start).Days;
    }

//托马斯

答案 4 :(得分:0)

我发现自己需要经常这样做,所以我创建了以下扩展方法。

public static DateTime FirstDateOfCalendarMonth(this DateTime dt, DayOfWeek firstDayOfWeek = DayOfWeek.Sunday)
{
  dt = new DateTime(dt.Year, dt.Month, 1);
  while (dt.DayOfWeek != firstDayOfWeek){
    dt = dt.AddDays(-1);
  }
  return dt;
}

像这样使用

var firstCalDate = DateTime.Now.FirstDateOfCalendarMonth();

它默认为星期日作为第一个DayOfWeek,但你可以将它传递给你喜欢的DayOfWeek,如下所示:

var firstCalDate = DateTime.Now.FirstDateOfCalendarMonth(DayOfWeek.Monday);

答案 5 :(得分:0)

DateTime start_date = Cal_start_date.SelectedDate;
DateTime end_date = Cal_end_date.SelectedDate;

Dictionary<string, int> dic_week_day = new Dictionary<string, int>();
dic_week_day["Sunday"] = 1;
dic_week_day["Monday"] = 2;
dic_week_day["Tuesday"] = 3;
dic_week_day["Wednesday"] = 4;
dic_week_day["Thursday"] = 5;
dic_week_day["Friday"] = 6;
dic_week_day["Saturday"] = 7;

DateTime first_day = start_date.AddDays(1 - start_date.Day);
int selected_day = dic_week_day[Drp_day_of_week.SelectedValue.ToString()];

string str_html = "";
for (DateTime i = first_day; i <= end_date; i = i.AddMonths(1))
{
    int day_of_week = dic_week_day[i.DayOfWeek.ToString()];
    DateTime temp_date;
    if (day_of_week > selected_day)
    {
        temp_date = i.AddDays((7 - day_of_week) + selected_day);
    }
    else
    {
        temp_date = i.AddDays(selected_day - day_of_week);
    }

    DateTime last_day_of_month = (temp_date.AddMonths(1)).AddDays(-temp_date.Day);

    if (Drp_occurrence.SelectedValue.ToString() == "odd")
    {
        if (start_date <= temp_date && temp_date <= end_date && temp_date <= last_day_of_month)
        {
            str_html += "<br />" + temp_date.ToString();
        }

        DateTime res_date = temp_date.AddDays(14);

        if (start_date <= res_date && res_date <= end_date && res_date <= last_day_of_month)
        {
            str_html += "  ,  " + res_date.ToString();
        }

        res_date = temp_date.AddDays(28);

        if (start_date <= res_date && res_date <= end_date && res_date <= last_day_of_month)
        {
            str_html += "  ,  " + res_date.ToString();
        }
    }
    else if (Drp_occurrence.SelectedValue.ToString() == "even")
    {
        DateTime res_date = temp_date.AddDays(7);

        if (start_date <= res_date && res_date <= end_date && res_date <= last_day_of_month)
        {
            str_html += "<br />" + res_date.ToString();
        }

        res_date = temp_date.AddDays(21);

        if (start_date <= res_date && res_date <= end_date && res_date <= last_day_of_month)
        {
            str_html += "  ,  " + res_date.ToString();
        }
    }
    else
    {
        int occurrence = Int32.Parse(Drp_occurrence.SelectedValue.ToString());

        DateTime res_date = temp_date.AddDays((occurrence - 1) * 7);

        if (start_date <= res_date && res_date <= end_date && res_date <= last_day_of_month)
        {
            str_html += "<br />" + res_date.ToString();
        }
    }
}

Div_result.InnerHtml = str_html;

答案 6 :(得分:-1)

更新:以下代码有错误!使用模运算,以补偿环境,.NET在星期天开始一周!请参阅此处的其他解决方案(没有额外功能的解决方案)。

如果您需要找到“27”(即显示一个月的第一天),只需使用:

DateTime monthStart = new DateTime(year, month, 1); 
DateTime monthDisplayStart = monthStart.AddDays(-((int)monthStart.DayOfWeek - 1));