Justin Adkins
Justin Adkins

Reputation: 1234

For Each statement for DayOfWeek Enum

I have two DateTime values called StartDate and EndDate. by default they only span the period of a week, however, the user can expand them farther.

I'm trying to write a HTML table that will insert rows foreach day in that span of time.

For example:

foreach DayOfWeek in (StartDate thru EndDate)<br/>
OUTPUT
 <tr>
  <th>[DAYOFWEEK]</th>
 </tr>

Upvotes: 0

Views: 637

Answers (2)

J&#252;rgen Steinblock
J&#252;rgen Steinblock

Reputation: 31723

Not tested, but should work.

var startDate = new DateTime(2014, 2, 20);
var endDate = new DateTime(2014, 3, 10);

var days = (endDate - startDate).TotalDays;

Console.WriteLine("<tr>");
for(int i = 0; i <= days; i++)
{
   var theDate = startDate.AddDays(i);
   Console.WriteLine("<th>{0}</th>", theDate.DayOfWeek);
}
Console.WriteLine("</tr>");

Update

Just got inspired to write this little helper

public static class DateTimeHelper
{
    public static void ForEach(DateTime from, DateTime to, Action<DateTime> action)
    {
        if (to < from)
            for (DateTime date = from; date.Date >= to.Date; date = date.AddDays(-1))
                action.Invoke(date);
        else
            for (DateTime date = from; date.Date <= to.Date; date = date.AddDays(1))
                action.Invoke(date);
    }
}

Usage

DateTimeHelper.ForEach(startDate, endDate, date =>
{
    Console.WriteLine(date);
});

Update2: fixed ForEach support for EndDate > StartDate

Upvotes: 6

Anirudha Gupta
Anirudha Gupta

Reputation: 9289

@{
    DateTime start = new DateTime(2013, 08, 12);
    DateTime end = new DateTime(2013, 08, 24);


    for (DateTime d = start; d < end; d = d.AddDays(1))
    {
        @(d.ToString()) <br/>
    }
}

Upvotes: 0

Related Questions