Get last/next week Wednesday date in C#

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

    Based on Servy's answer, here's an extension method which will return the desired day/date:

        public static DateTime GetPrevious(this DateTime date, DayOfWeek dayOfWeek)
        {
            var lastDay = date.AddDays(-1);
            while (lastDay.DayOfWeek != dayOfWeek)
            {
                lastDay = lastDay.AddDays(-1);
            }
    
            return lastDay;
        }
    
        public static DateTime GetNext(this DateTime date, DayOfWeek dayOfWeek)
        {
            var nextDay = date.AddDays(+1);
            while (nextDay.DayOfWeek != dayOfWeek)
            {
                nextDay = nextDay.AddDays(+1);
            }
    
            return nextDay;
        }
    

提交回复
热议问题