Get next 6 months from date passed in to method

TheCoder 91 Reputation points
2022-06-08T19:39:25.13+00:00

I'm going to have 2 dropdowns that are populated with dates.

Dropdown 1 has dates populated as such
3/1/2021
2/1/2021
1/1/2021
12/1/2020

and so on

[ this is the part I need help with, the first drop down is working ]
When the user selects a date in the first drop down, it'll pass the selected date into another method which will populate dates as I need the second drop down to show dates as such:
6/1/2021
7/1/2021
8/1/2021
9/1/2021

and so on, and returned in JSON Format.

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,326 Reputation points
    2022-06-08T19:52:15.287+00:00

    I'm not quite sure what your question is. Since you already seem to have an API that returns dates and you have already hooked up a dropdown then I assume the issue isn't with getting the data/updating UI but rather just getting the 6 months of dates. For that just add 6 to the month number.

       public static IEnumerable<DateTime> GetNextMonths ( DateTime startDate, int months )  
       {  
           for (var index = 1; index <= months; ++index)  
               yield return startDate.AddMonths(index);  
       }  
         
       var next6Months = GetNextMonths(startDate, 6);  
    

    Assumption here is that you want exactly 6 months, bearing in mind that some dates (like 1/31) would not properly translate 1 month but that is probably not an issue.

    If you want a slightly more elegant, but properly less efficient approach then.

       var next6Months = Enumerable.Range(1, 6).Select(x => startDate.AddMonths(x));  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.