我正在寻找一些逻辑,以便在给定日期的同一天(例如:星期三)和同一周(例如:第一或第二......)的N个月后获得日期。
ex:12-06-2013(6月的周三和第3周)是给定日期。 在这里,我将在给定日期增加3个月。 结果应该是2013年8月14日(星期三和8月的第3周)。
如果您需要更多说明,请告诉我。
提前致谢。
答案 0 :(得分: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);
}
这是完全未经测试的 - 你应该绝对有一堆单元测试(理想情况下,你甚至可以在编写这些代码之前编写)测试你感兴趣的各种边缘情况。< / p>
答案 1 :(得分: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++;
}
=&GT; 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--;
}
=&GT; newDate将是Augus 10,2013
6) Calculte required date
newDate.AddDays(DayofWeek) =>newDate will be August 14,2013