Get last/next week Wednesday date in C#

前端 未结 13 1646
情话喂你
情话喂你 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:16

    Use the AddDays routine:

            // increment by the number of offset days to get the correct date
            DayOfWeek desiredDay = DayOfWeek.Wednesday;
            int offsetAmount = (int) desiredDay - (int) DateTime.Now.DayOfWeek;
            DateTime lastWeekWednesday = DateTime.Now.AddDays(-7 + offsetAmount);
            DateTime nextWeekWednesday = DateTime.Now.AddDays(7 + offsetAmount);
    

    That should do it!

    NOTE: If it is a Monday, "Last Wednesday" is going to give you the very last Wednesday that occurred, but "Next Wednesday" is going to give you the Wednesday 9 days from now! If you wanted to get the Wednesday in two days instead you would need to use the "%" operator. That means the second "nextweek" statement would read "(7 + offsetAmount) % 7".

提交回复
热议问题