Get last/next week Wednesday date in C#

前端 未结 13 1695
情话喂你
情话喂你 2021-02-18 19:50

How would I get last week Wednesday and next week Wednesday\'s date in C#:

public Form1()
{
   InitializeComponent();
   CurrentDate.Text = \"Today\'s Date: \" +         


        
13条回答
  •  一整个雨季
    2021-02-18 19:56

    Here is a one-liner to accomplish the same. It is somewhat mind-boggling to understand how that actually works but it does:

    Getting next Wednesday:

     dt.AddDays(-(int)(dt.AddDays(-4).DayOfWeek) + 6);
    

    Getting last Wednesday

     dt.AddDays(-(int)(dt.AddDays(-3).DayOfWeek));
    

    In both cases, it will return the day itself when it is Wednesday. This works for any weekdays, just adjust the number in the AddDays() call. For example for Friday:

    Getting next Friday

     dt.AddDays(-(int)(dt.AddDays(-6).DayOfWeek) + 6);
    

    Getting last Friday

     dt.AddDays(-(int)(dt.AddDays(-5).DayOfWeek));
    

提交回复
热议问题