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.





LVL 6
RustyZ32Asked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Lots of ways to do it...

            DateTime dt = DateTime.Today.AddDays(-1);
            while (dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Saturday)
                dt = dt.AddDays(-1);
            string ShortDate = dt.ToShortDateString();
0
 
NauticalNonsenseCommented:
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?
0
 
NauticalNonsenseCommented:
Pretty sneaky, sis.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
RustyZ32Author Commented:
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.
0
 
NauticalNonsenseConnect With a Mentor Commented:
using Idle's code:

TBenddate.Text = ShortDate;
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
*Tag Team* Thanks Nautical.  =)
0
 
RustyZ32Author Commented:
that worked! I changed the values to monday and sunday to test, worked like a charm.


thanks to you both.
0
 
NauticalNonsenseCommented:
Your loop was adorable... love it!
Cheers!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.