Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if date range is sequential in c#?

Tags:

c#

.net-2.0

Assume I have a user interface where the user can select days. Is there a way to check if the days selected are sequential, such as:

4/4, 4/5, 4/6, 4/7, 4/8, 4/9, 4/10 or

4/29, 4/30, 5/1, 5/2, 5/3

I know I probably can loop through the date range and check, but I was more curious if there was a built in method already to check for this.

Regarding the above scenarios, they are in order and they can roll over into the next month.

I am using the .NET Framework 2.0 and can't use LINQ.

Regarding Tom's answer:

DateTime dtStart = new DateTime(2011,5,4);
DateTime dtEnd = new DateTime(2011,5,11);

int numberOfDaysSelected = 7; //Assume 7 days were selected.

TimeSpan ts = dtEnd - dtStart;


if(ts.Days == numberOfDaysSelected - 1)
{
Console.WriteLine("Sequential");
}
else
{
Console.WriteLine("Non-Sequential");
}
like image 849
Xaisoft Avatar asked May 04 '11 16:05

Xaisoft


2 Answers

I do not believe there is a built in method to achieve your desired results but if you can easily tell the earliest and latest dates, you could create a new TimeSpan by subtracting the the earliest date from the latest date and then verifying that the number of days of the timespan matches the number of dates selected - 1.

like image 165
Tom Avatar answered Oct 10 '22 10:10

Tom


Nothing built in but you can build one easily using Linq:

List<DateTime> timeList = new List<DateTime>();
//populate list..
bool isSequential = timeList.Zip(timeList.Skip(1), 
                                 (a, b) => b.Date == a.Date.AddDays(1))
                            .All(x => x);

Edited - misunderstood question first to mean ascending in time as opposed to sequential - fixed that.

like image 25
BrokenGlass Avatar answered Oct 10 '22 08:10

BrokenGlass