Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to populate 30 days from now using Enumerable.Range(1,31)

but we know that some months have 30 days and some have 28 days.
so I have added condition but it doesnt work well.

is there any other method I can do this.

I want a collection of 30 days from now. suppose today is Jan 15 so I want all dates from Jan 15 to Feb 14. (30 days from now irrespective of month or day).
currently I am using this below: but it is not proper.

What I have tried:

Enumerable.Range(1, 31).Select(day =>
            {
                var date = new DateTime();                
                if (day <= 28)
                {
                    date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, day);
                    date = date.BeginningOfDay();
                }
                else
                {
                    count++;
                    date = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, count);
                }
                if (date < DateTime.Now.BeginningOfDay()) date = date.AddMonths(1);

                return date;

            }).OrderBy(d => d.Date).ToList();
Posted
Updated 1-Feb-19 0:00am
v2

1 solution

Enumerable.Range(1, 31).Select(day =>
                DateTime.Now.AddDays(day)).ToList();
 
Share this answer
 
Comments
CPallini 1-Feb-19 6:28am    
Neat.
Maciej Los 5-Feb-19 9:38am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900