Link to home
Start Free TrialLog in
Avatar of tbaseflug
tbaseflugFlag for United States of America

asked on

Get previous Friday

I need a way to always get the previous friday in a string?
Avatar of p_davis
p_davis

int daysSub = 1;

DateTime tempDate = new DateTime();

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


DateTime yourLastFriday = tempDate;
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

ps... did not test
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)
also -- there is no subtractdays =) sorry
so you will have to use the .AddDays(-x);
Avatar of tbaseflug

ASKER

SubtractDays?  is that c# compat?
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

very strange - both solutions return 10/28/2011 - I checked the date on the server and it is marked for today...
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am an idiot - wrong calendar - whoops