使用c#传递dayofweek,weekofmonth,monthofyear和year获取日期

时间:2015-11-05 05:54:00

标签: c#

我需要一种方法,它可以在获得4个输入,dayofweek,weekofmonth,monthofyear和year之后返回日期。我已经尝试过以下但是当月份的第4个星期没有所有日子时它失败了,所以我回到28更安全的一面。如果可能的话,我想有一个完整的解决方案,并且比这更好。请忽略我的参数,我知道我可以通过传递日期来改进它。这是我的代码;

public static DateTime GetDateByDayOfWeekOfMonthOfYear(int dayOfWeek, int weekOfMonth, int monthOfYear, int year)
        {
            var firstDayOfMonth = new DateTime(year, monthOfYear, 1);
            var firstDay = (int)firstDayOfMonth.DayOfWeek;
            var addor = 0;
            if (firstDay == (int)DayOfWeek.Monday)
                addor = 0;
            if (firstDay == (int)DayOfWeek.Tuesday)
                addor = 6;
            if (firstDay == (int)DayOfWeek.Wednesday)
                addor = 5;
            if (firstDay == (int)DayOfWeek.Thursday)
                addor = 4;
            if (firstDay == (int)DayOfWeek.Friday)
                addor = 3;
            if (firstDay == (int)DayOfWeek.Saturday)
                addor = 2;
            if (firstDay == (int)DayOfWeek.Sunday)
                addor = 1;
            var resultantDate = firstDayOfMonth.AddDays((7 * weekOfMonth + addor) - (7 - dayOfWeek) - 1);

             return resultantDate.Month == monthOfYear
            ? resultantDate
            : firstDayOfMonth.AddDays(27);
        }

1 个答案:

答案 0 :(得分:1)

你可以这样做 - 对于你选择的工作日,以及这个工作日的第一次或更晚的事件:

// Select year, month, weekday, and occurrence of weekday.
int year = 2015;
int month = 10;
DayOfWeek dayOfWeek = DayOfWeek.Monday;
int occurrence = 1;  // Valid values: 1 to 5.

// Constants.
const int daysInWeek = 7;
const int maximumWeek = 5;
const int minimumWeek = 1;

occurrence = occurrence < minimumWeek ? minimumWeek : occurrence;
occurrence = occurrence > maximumWeek ? maximumWeek : occurrence;

DateTime first = new DateTime(year, month, 1);
int primoOffset = (dayOfWeek - first.DayOfWeek  + daysInWeek) % daysInWeek;
DateTime dayInMonth = first.AddDays(primoOffset + daysInWeek * --occurrence);
if (dayInMonth.Month != month)
{
    // Week 5 belongs to the next month.
    // Return value for the last occurrence.
    dayInMonth = dayInMonth.AddDays(-daysInWeek);
}

return dayInMonth;