Reputation: 2601
How would I be able to get the date of the Thursday in the current week? For example, Thursday of this current week is 7/8/2010
Upvotes: 8
Views: 7187
Reputation: 102448
// This is fixed...
int thursday = 4;
int difference = thursday - (int)DateTime.Now.DayOfWeek;
DateTime thursdayThisWeek = DateTime.Now.Date.AddDays(difference);
Upvotes: 0
Reputation: 50710
Pseudo code to find nearest Thursday:
for 0 to 3 as x
if today + x days is Thursday
return (today + x days)
if today - x days is Thursday
return (today - x days)
Pseudo code to find Thursday this week:
lookForward = true
lookBackward = true
FirstDayOfTheWeek = Sunday
for 0 to 6 as x
if today + x days is FirstDayOfTheWeek
lookForward = false
if today - x days is FirstDayOfTheWeek
lookBackward = false
if lookForward and today + x days is Thursday
return (today + x days)
if lookBackward and today - x days is Thursday
return (today - x days)
Sorry, I don't speak C# :)
Upvotes: 0
Reputation: 78292
private static DateTime GetDayOfWeek(DayOfWeek dayOfWeek)
{
var date = DateTime.Now;
if (date.DayOfWeek != dayOfWeek)
{
var direction = date.DayOfWeek > dayOfWeek ? -1D : 1D;
do
{
date = date.AddDays(direction);
} while (date.DayOfWeek != dayOfWeek);
}
return date;
}
Upvotes: 1
Reputation: 131806
You can do this (alebit awkwardly) with the existing .NET DateTime. The trick is to use the DayOfWeek
enum as an integer - since it denotes the days Sun - Sat in ascending numeric order (0-6).
DateTime someDay = DateTime.Today;
var daysTillThursday = (int)someDay.DayOfWeek - (int)DayOfWeek.Thursday;
var thursday = someDay.AddDays( daysTillThursday );
Or even more simply:
var today = DateTime.Today;
var thursday = today.AddDays(-(int)today.DayOfWeek).AddDays(4);
Upvotes: 17
Reputation: 6478
Check out this library: http://datetimeextensions.codeplex.com/
From the examples on the home page:
DateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);
Upvotes: 1