我正在寻找一些逻辑来获取给定日期的同一天(例如:星期三)和同一周(例如:第一或第二...)的 N 个月后的日期。
例如:12-06-2013(星期三和六月第三周)是指定日期。 在这里,我在给定日期的基础上添加了 3 个月。 结果应该是2013年8月14日(星期三和8月第三周)。
如果您需要更多说明,请告诉我。
提前致谢。
最佳答案
好的,所以我个人会使用我的 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);
}
不过,这完全未经测试 - 您绝对应该进行一堆单元测试(最好是在包含此代码之前编写)来测试您感兴趣的各种边缘情况。
关于c# - 如何获取给定日期的N个月后同一天和同一周的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17059492/