Get last/next week Wednesday date in C#

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

    You could create 2 DateTime Extension methods, that can be used with a DayOfWeek parameter:

    public static class DateTimeExtension
    {
        public static DateTime GetPreviousWeekDay(this DateTime currentDate, DayOfWeek dow)
        {
            int currentDay = (int)currentDate.DayOfWeek, gotoDay = (int)dow;
            return currentDate.AddDays(-7).AddDays(gotoDay-currentDay);
        }
    
        public static DateTime GetNextWeekDay(this DateTime currentDate, DayOfWeek dow)
        {
            int currentDay = (int)currentDate.DayOfWeek, gotoDay = (int)dow;
            return currentDate.AddDays(7).AddDays(gotoDay - currentDay);
        }
    }
    

    Which can then be used as follows:

    DateTime testDate = new DateTime(2017, 01, 21);
    
    Console.WriteLine(testDate.GetPreviousWeekDay(DayOfWeek.Wednesday));
    Console.WriteLine(testDate.GetNextWeekDay(DayOfWeek.Wednesday));
    

提交回复
热议问题