We help IT Professionals succeed at work.

Get previous Friday

tbaseflug
tbaseflug asked
on
I need a way to always get the previous friday in a string?
Comment
Watch Question

CERTIFIED EXPERT

Commented:
int daysSub = 1;

DateTime tempDate = new DateTime();

while(DateTime.Now.SubtractDays(daysSub).DayOfWeek != DayOfWeek.Friday)
{
        daysSub++;
        tempDate = DateTime.Now.SubtractDays(daysSub);
}


DateTime yourLastFriday = tempDate;
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
If you have a DateTime instance, then you can use a loop to find the previous Friday:

DateTime d = DateTime.Now;

while (d.DayOfWeek != DayOfWeek.Friday)
{
    d = d.AddDays(-1);
}

Open in new window

CERTIFIED EXPERT

Commented:
ps... did not test
CERTIFIED EXPERT

Commented:
kaufmed your's is way more streamlined but it won't work if today's date is friday and you still want the last friday.


(nice work btw)
CERTIFIED EXPERT

Commented:
also -- there is no subtractdays =) sorry
CERTIFIED EXPERT

Commented:
so you will have to use the .AddDays(-x);

Author

Commented:
SubtractDays?  is that c# compat?
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
but it won't work if today's date is friday and you still want the last friday.

Aww... shucks  ={D

How about:

while (d.DayOfWeek != DayOfWeek.Friday)
{
    d = d.AddDays(1);
}

d = d.AddDays(-7);

Open in new window

Author

Commented:
very strange - both solutions return 10/28/2011 - I checked the date on the server and it is marked for today...
Freelance programmer / Consultant
CERTIFIED EXPERT
Commented:
Trivial alteration to the code from Kaufmed:


DateTime d = DateTime.Now.AddDays(-1);  //Just in case today is a Friday

while (d.DayOfWeek != DayOfWeek.Friday)
{
    d = d.AddDays(-1);
}
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
@AndyAinscow
You shouldn't need the alteration to the logic. If today is Friday, then you wouldn't want to enter the loop, and you would simply subtract seven days. The addition means there will be one needless iteration of the loop.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
@AndyAinscow
Never mind. I see now you were altering my first suggestion.

Author

Commented:
I am an idiot - wrong calendar - whoops

Explore More ContentExplore courses, solutions, and other research materials related to this topic.