I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS
+2
A:
DateTime startDate;
DateTime endDate;
DateTime currentDate = startDate;
List<DateTime> dates = new List<DateTime> ();
while (true)
{
dates.Add (currentDate);
if (currentDate.Equals (endDate)) break;
currentDate = currentDate.AddDays (1);
}
It assumes that startDate < than endDate, you get the results on the "dates" list
AlbertEin
2008-10-02 16:29:43
I know in VB.NET AddDays returns a date object that needs to be assigned. It would be used like this "currentDate = currentDate.AddDays(1). I'm not sure if that's the same in C# though.
Stephen Wrighton
2008-10-02 16:32:26
You were right, thanks
AlbertEin
2008-10-02 16:34:07
A:
public static List<DateTime> CreateDateRange(DateTime startDate, DateTime endDate)
{
List<DateTime> result = new List<DateTime>();
DateTime current = startDate.Date;
while (current.Date <= endDate.Date)
{
result.Add(current);
current = current.Date.AddDays(1);
}
return result;
}
Mitch Wheat
2008-10-02 16:35:36
+1
A:
I voted up AlbertEin because he gave a good answer, but do you really need a collection to hold all the dates? When you are rendering the day, couldn't you just check if the date is withing the specified range, and then render it differently, no need for a collection. Here's some code to demonstrate
DateTime RangeStartDate,RangeEndDate; //Init as necessary
DateTime CalendarStartDate,CalendarEndDate; //Init as necessary
DateTime CurrentDate = CalendarStartDate;
String CSSClass;
while (CurrentDate != CalendarEndDate)
{
if(CurrentDate >= RangeStartDate && CurrentDate <= RangeEndDate)
{
CSSClass= "InRange";
}
else
{
CSSClass = "OutOfRange";
}
//Code For rendering calendar goes here
currentDate = currentDate.AddDays (1);
}
Kibbee
2008-10-02 16:37:25
+1
A:
IEnumerable<DateTime> RangeDays(DateTime RangeStart, DateTime RangeEnd) {
DateTime EndDate = RangeEnd.Date;
for (DateTime WorkDate = RangeStart.Date; WorkDate <= EndDate; WorkDate = WorkDate.AddDays(1)) {
yield return WorkDate;
}
yield break;
}
Untested code... but should work.
spoulson
2008-10-02 16:38:14
+1
A:
// inclusive
var allDates = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(i => startDate.AddDays(i));
// exclusive
var allDates = Enumerable.Range(1, (endDate - startDate).Days).Select(i => startDate.AddDays(i));
Mark Brackett
2008-10-02 16:56:22