2

我正在寻找一些逻辑来获取在给定日期的同一天(例如:星期三)和同一周(例如:第一或第二...)的 N 个月之后的日期。

例如:12-06-2013(星期三和六月的第三周)是给定的日期。在这里,我将给定日期增加 3 个月。结果应该是 2013 年 8 月 14 日(星期三和八月的第三周)。

如果您需要更多说明,请告诉我。

提前致谢。

4

2 回答 2

3

好的,所以我会亲自使用我的Noda Time库来执行此操作。使用 完全可以做到这一点DateTime,但我个人觉得更难。当然,我还鼓励您使用Noda Time作为更好的日期/时间 API。所以我会有类似的东西:

static LocalDate AddMonthsPreserveWeekDayAndWeek(LocalDate start, int months)
{
    // This isn't the week of month in the "normal" sense; it's the nth
    // occurrence of this weekday.
    int week = ((start.DayOfMonth - 1) / 7) + 1;

    // This will usually give the same day of month, but truncating where
    // necessary
    LocalDate monthsAdded = start.AddMonths(months);
    LocalDate endOfPreviousMonth = monthsAdded.AddDays(-monthsAdded.Day);

    // Get to the first occurrence of the right day-of-week
    LocalDate firstRightDay = endOfPreviousMonth.Next(start.IsoDayOfWeek);

    // Usually this will be right - but it might overflow to the next month,
    // in which case we can just rewind by a week.
    LocalDate candidate = firstRightDay.PlusWeeks(week - 1);
    return candidate.Month == firstRightDay.Month ? candidate
                                                  : candidate.PlusWeeks(-1);
}

不过,这完全未经测试——您绝对应该有一堆单元测试(最好是在包含此代码之前编写)来测试您感兴趣的各种边缘情况。

于 2013-06-12T07:37:42.797 回答
1

使用标准 MDSN 年 = 2013 月 = 06 日期 = 12

1)从特定日期获取星期几(星期日为0)

DateTime dateValue = new DateTime(year, month, date);  
Console.WriteLine((int) dateValue.DayOfWeek);      // Displays 3 implying it is Wed

2)从特定日期获取月份的星期几

DayofWeek = 3 (from previous calculation)
Day = 12 
EndOfWeek = Day + (6 - DayOfWeek) = 12 + 4 = 16  
NoWeek = 0
while (EndOfWeek > 0)
{
   EndOfWeek  -= 7;
   NoWeek++;        
}

=> 本周 = 3

3)在 N 个月后获取第一个日期

DateTime newDate = new DateTime(year, month, 1)

newDate.AddMonths(N); // Let it be 2 => August 1, 2013

4)获取新日期的星期几

newDay = newDate.DayOfWeek  // Return 4 implying Thursday

5)获取 NoWeek 之后的最后一天

newDate.AddDays(6-newDay) => newDate.AddDays (6-4) => August 3,2013
NoWeek--;
while (NoWeek > 1)
{
    newDate.AddDays(7);
    NoWeek--;
}

=> newDate 将是 2013 年 8 月 10 日

6)计算所需日期

newDate.AddDays(DayofWeek) =>newDate will be August 14,2013
于 2013-06-12T10:04:44.290 回答