Get last/next week Wednesday date in C#

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

    this extension method should do the trick for whatever dayofweek

       public static class DateTimeExtensions
        {
            public static DateTime LastDayOfWeek(this DateTime _date, DayOfWeek dayofweek)
            {
                return _date.AddDays(-1 * ((_date.DayOfWeek - dayofweek) % 7)).Date;
            }
    
            public static DateTime NextDayOfWeek(this DateTime _date, DayOfWeek dayofweek)
            {
                return _date.LastDayOfWeek(dayofweek).AddDays(7).Date;
            }
        }
    

    usage

    var lastWendsday = DateTime.Now.LastDayOfWeek(DayOfWeek.Wednesday);
    

提交回复
热议问题