Get last/next week Wednesday date in C#

前端 未结 13 1973
情话喂你
情话喂你 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 20:05

    This will work. You need to calculate the difference in days between your provided date and the nearest Wednesday, and calculate last/next Wednesday based on whether or not the difference is greater than zero.

    int difference = date.DayOfWeek - DayOfWeek.Wednesday;
    DateTime lastWednesday = difference > 0 ? date.AddDays(-1 * difference) : date.AddDays(-1 * (7 + difference));
    DateTime nextWednesday = lastWednesday.AddDays(7);
    

提交回复
热议问题