Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get All Dates in a given month in C#

Tags:

c#

list

datetime

I want to make a function that take month and year and return List<DateTime> filled with all dates in this month.

any help will be appreciated

Thanks in Advance

like image 517
Amira Elsayed Ismail Avatar asked Oct 03 '10 13:10

Amira Elsayed Ismail


3 Answers

Here's a solution with LINQ:

public static List<DateTime> GetDates(int year, int month)
{
   return Enumerable.Range(1, DateTime.DaysInMonth(year, month))  // Days: 1, 2 ... 31 etc.
                    .Select(day => new DateTime(year, month, day)) // Map each day to a date
                    .ToList(); // Load dates into a list
}

And one with a for-loop:

public static List<DateTime> GetDates(int year, int month)
{
   var dates = new List<DateTime>();

   // Loop from the first day of the month until we hit the next month, moving forward a day at a time
   for (var date = new DateTime(year, month, 1); date.Month == month; date = date.AddDays(1))
   {
      dates.Add(date);       
   }

   return dates;
}

You might want to consider returning a streaming sequence of dates instead of List<DateTime>, letting the caller decide whether to load the dates into a list or array / post-process them / partially iterate them etc. For the LINQ version, you can accomplish this by removing the call to ToList(). For the for-loop, you would want to implement an iterator. In both cases, the return-type would have to be changed to IEnumerable<DateTime>.

like image 164
Ani Avatar answered Nov 15 '22 15:11

Ani


Sample for pre-Linq Framework versions, using February 1999.

int year = 1999;
int month = 2;

List<DateTime> list = new List<DateTime>();
DateTime date = new DateTime(year, month, 1);

do
{
  list.Add(date);
  date = date.AddDays(1);
while (date.Month == month);
like image 35
Steve Townsend Avatar answered Nov 15 '22 13:11

Steve Townsend


I am sure there might be better ways to do this. But, you could use this:

public List<DateTime> getAllDates(int year, int month)
{
    var ret = new List<DateTime>();
    for (int i=1; i<=DateTime.DaysInMonth(year,month); i++) {
        ret.Add(new DateTime(year, month, i));
    }
    return ret;
}
like image 4
Pablo Santa Cruz Avatar answered Nov 15 '22 15:11

Pablo Santa Cruz