Reputation: 7826
I'm using the following to get the current week number:
var weekNo = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.UtcNow,
CalendarWeekRule.FirstFullWeek,
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#?
Upvotes: 2
Views: 1291
Reputation: 14640
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.
Upvotes: 4
Reputation:
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
Upvotes: 0
Reputation: 160852
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);
Upvotes: 3
Reputation: 19765
Could you add the number of days from now until Sunday, and then add (n-1)*7 more days?
Upvotes: 1