Link to home
Start Free TrialLog in
Avatar of RustyZ32
RustyZ32Flag for United States of America

asked on

C# subtract 1 day from current day only when weekdays

I have this line which subtracts 1 day from the current date (to populate a textbox):

DateTime.Now.AddDays(-1).ToShortDateString();

How can I do the same but have it ignore weekend days? for example, on monday it would subtract 1 day but skip over sunday and saturday to return the value for friday.

In other words, how can I subtract 1 weekday from the current day.





Avatar of NauticalNonsense
NauticalNonsense
Flag of United States of America image

DateTime dateTime = DateTime.Now;
                DateTime prePopulate = new DateTime();
            if (dateTime.DayOfWeek == System.DayOfWeek.Monday)
                prePopulate = dateTime.AddDays(-3);
            else
                prePopulate = dateTime.AddDays(-1);

What are you doing on Saturday and Sunday? Or are you assuming nobody uses this on Sunday?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America 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
Pretty sneaky, sis.
Avatar of RustyZ32

ASKER

Ok, how can I set a textbox value using these?

my old line is as follows:

TBenddate.Text = DateTime.Now.AddDays(-1).ToShortDateString();

I've tried a few different ways and can't seem to get the syntax correct.
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
*Tag Team* Thanks Nautical.  =)
that worked! I changed the values to monday and sunday to test, worked like a charm.


thanks to you both.
Your loop was adorable... love it!
Cheers!