开发者

Get DateTime for the nth Sunday after today

I'm using the following to get the current week number:

var weekNo = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.UtcNow,
                                                  CalendarWeekRule.FirstFullWeek,
                                开发者_StackOverflow                  DayOfWeek.Sunday);

And I want to return the DateTime representing the first day of the nth week after today.

e.g. when n = 2, I would want the DateTime representing the Sunday after next.

Is there a way I can do this in C#?


You could use:

DateTime sundayInFuture = DateTime.Today.AddDays((n - 1) * 7 + (7 - (int)DateTime.Today.DayOfWeek));

That should work (though I've not got access to anything to test it!).

Edit: Thanks to the comments.


This should work:

int n = 2;
DateTime today = DateTime.Today;
int daysToNextSunday = (7 - today.DayOfWeek - DayOfWeek.Sunday) ;
DateTime nthSunday = today.AddDays((n - 1) * 7 + daysToNextSunday);


Could you add the number of days from now until Sunday, and then add (n-1)*7 more days?


Please note, that Calendar.GetWeekOfYear is not ISO 8601 conform.

Here a sample Using the Week class of the Time Period Library for .NET:

// ----------------------------------------------------------------------
public DateTime GetStartOfWeek( DateTime moment, int offset )
{
  return new Week( new Week( moment ).WeekOfYear + Math.Abs( offset ) ).FirstDayOfWeek;
} // GetStartOfWeek
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜