簡體   English   中英

如何在給定日期的同一天和同一周的N個月后獲取日期

[英]How to get date after N months with same day and same week of a given date

我正在尋找某種邏輯來獲取給定日期的同一天(例如:星期三)和同一周(例如:第一或第二...)的N個月后的日期。

例如:2013年12月6日(六月的星期三和第三周)是給定的日期。 在這里,我將給定日期增加3個月。 結果應為2013年8月14日(星期三和8月的第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);
}

不過,這是完全未經測試的-您絕對應該有一堆單元測試(理想情況下是在編寫此代碼之前編寫的),這些單元測試可以測試您感興趣的各種邊緣情況。

使用標准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++;        
}

=> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM