如何将下个月的星期三作为DateTime?

时间:2014-07-11 13:36:27

标签: c# datetime

我需要一个函数,它给出了下个月的第n个DateTime。 例如:我需要下个月的第四个星期三。

我的代码提供错误的日期:

private static DateTime FindNextDay(DayOfWeek dayOfWeek, DateTime fday, Int32 instance)
{
    DateTime day = new DateTime(fday.Year, fday.Month, 1, fday.Hour, fday.Minute, fday.Second);
    // DateTime day is in this Example= 2014-08.01 11.00 AM   
     if (instance == 2)
     {
         day = day.AddDays(7);
     }
     else if (instance == 3)
     {
         day = day.AddDays(14);
     }
     else if (instance == 4)  //if the 4th week is requested
     {
         day = day.AddDays(28); // i add 28 days
     }
     while (day.DayOfWeek != dayOfWeek)
     {
         day = day.AddDays(1);   // and search the wednesday and return it back
     }
    return day;
}

你能告诉我一个更好的解决方案吗?

3 个答案:

答案 0 :(得分:3)

像这样......

获取下个月的第一天,记下您在找到时添加的wednesdays次数。当计数为4时返回。

private static DateTime GetFourthWednesday()
{
    DateTime firstOfMonth = new DateTime(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month, 1);

    int count = 0;
    while (count < 4)
    {
        if (firstOfMonth.DayOfWeek == DayOfWeek.Wednesday)
        {
            count++;
        }

        if (count == 4)
        {
            return firstOfMonth;
        }

        firstOfMonth = firstOfMonth.AddDays(1);

    }

    return firstOfMonth;
}

如果今天运行,则提供27/08/2014

答案 1 :(得分:1)

将最后的其他内容更改为:

else if (instance == 4)  //if the 4th week is requested
    {
        day = day.AddDays(21); // i add 28 days
    }

你应该增加21天而不是28天。

答案 2 :(得分:1)

因为我太懒了,所以我写了我的代码;

DateTime firstDayOfNextMonth = new DateTime(2014, DateTime.Now.Month + 1, 1);
int count = 0;
    if (firstDayOfNextMonth.DayOfWeek == DayOfWeek.Wednesday)
        count = 1;
while (count != 4)
{
    firstDayOfNextMonth = firstDayOfNextMonth.AddDays(1);
    if (firstDayOfNextMonth.DayOfWeek == DayOfWeek.Wednesday)
        count++;
}
Console.WriteLine(firstDayOfNextMonth);

基本上,我检查下个月的第一天是否为Wednesday,然后我会在下个月的星期三迭代我的DateTime找到4.

它今天正在运行,它会打印27.08.2014,这是下个月的第Wednesday个。{/ p>

您可以编写类似;

的扩展方法
public static class DateTimeExtensions
{
    public static void FindInstanceNextMonth(DateTime Now, DayOfWeek day, int instance)
    {
        DateTime firstDayOfNextMonth = new DateTime(Now.Year, Now.Month + 1, 1);
        int count = 0;
        if (firstDayOfNextMonth.DayOfWeek == day)
            count = 1;
        while (count != instance)
        {
            firstDayOfNextMonth = firstDayOfNextMonth.AddDays(1);
            if (firstDayOfNextMonth.DayOfWeek == day)
                count++;
        }
        Console.WriteLine(firstDayOfNextMonth);
    }
}

并称之为;

DateTimeExtensions.FindInstanceNextMonth(DateTime.Now, 
                                         DayOfWeek.Wednesday,
                                         4);