Vignesh Murugan
Vignesh Murugan

Reputation: 575

Generate Dates in C#

Is there any helper methods to generate Dates in C#?

For example I have a Grid which shows Date,Day of all dates between given two dates.. If i select 1/1/2013 to 2/5/2013...It should Generate all dates between these two...

I tried While Loop as follows

 while (startdate <= enddate)
 {         
      var calendarDate = CreateDate();
      calendarDate.CalendarDate = startdate.Date;
      if (calendarDate.DayofWeek == DayOfWeekValues.Sunday.Value)
      {
           calendarDate.IsHoliday = true;
      }       
      startdate = startdate.AddDays(1.0);
 }

Upvotes: 1

Views: 417

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460098

It's not clear what's wrong with your loop, it looks as if you just have to add the dates to a collection like a List<DateTime>. However, you could also use LINQ:

int days = (enddate - startdate).Days + 1;
List<DateTime> dateRange = Enumerable.Range(0, days)
    .Select(i => startdate.AddDays(i))
    .ToList();

Edit: since you don't use a DateTime but a custom class:

I don't know the class and methods involved, however, this should help to implement the same logic as you in your loop(presuming HolidayCalendarDetail is the class):

List<HolidayCalendarDetail> dates = Enumerable.Range(0, days)
.Select(i => 
{
    var calendarDate = e.CreateHolidayCalendarDetail();
    calendarDate.CalendarDate = startdate.AddDays(i);
    calendarDate.IsHoliday = calendarDate.CalendarDate.DayOfWeek == JobScheduleDayOfWeekValues.Sunday.Value;
    return calendarDate;
}).ToList();

Upvotes: 8

Henry Wilson
Henry Wilson

Reputation: 3351

This has already been covered over here: Exploding a range of dates with LINQ

I don't think there is a built in .Net helper but you can certainly achieve it with LINQ or a while loop.

Upvotes: 0

Related Questions