在ASP.NET中找到10月的最后一个星期日c#

时间:2009-11-25 07:51:31

标签: c# asp.net

斐伊川, 有没有办法找出ASP.NET中10月的最后一个星期日的日期# 我正在使用.net 2.0

4 个答案:

答案 0 :(得分:16)

没有必要为此运行循环:

private static DateTime GetLastWeekdayOfMonth(DateTime date, DayOfWeek day)
{
    DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
        .AddMonths(1).AddDays(-1);
    int wantedDay = (int)day;
    int lastDay = (int)lastDayOfMonth.DayOfWeek;
    return lastDayOfMonth.AddDays(
        lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
}

这很容易转换为扩展方法,如下所示:

public static class DateTimeExtensions
{
    public static DateTime GetLastWeekdayOfMonth(this DateTime date, DayOfWeek day)
    {
        DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
            .AddMonths(1).AddDays(-1);
        int wantedDay = (int)day;
        int lastDay = (int)lastDayOfMonth.DayOfWeek;
        return lastDayOfMonth.AddDays(
            lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
    }
}

...然后可以直接在任何DateTime对象中使用:

DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);

更新:修正了一个错误。

答案 1 :(得分:0)

您可以尝试这样的事情

DateTime date = new DateTime(2009, 10, 01);
date = date.AddMonths(1).AddDays(-1);
while (date.DayOfWeek != DayOfWeek.Sunday) date = date.AddDays(-1);

或尝试

date = date.AddDays(-(int)date.DayOfWeek);

答案 2 :(得分:0)

DateTime current = new DateTime(DateTime.Today.Year, 
    10, DateTime.DaysInMonth(DateTime.Today.Year, 10));

while (current.DayOfWeek != DayOfWeek.Sunday)
{
    current = current.AddDays(-1);
}

Console.WriteLine(current.ToLongDateString());

我把它打开了,所以你可以很容易地用月份换掉月份。

答案 3 :(得分:-2)

抱歉

arr1 && arr1[i]

错了!

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