Reputation: 2550
I'm doing this test-app and what it has to do is go through a long list of dates from a text file and get the missing ones (excluding weekend days) and write the results to an output file. If the missing date is a single day the output should be ccyy/mm/dd , if it's more than one day it should be ccyy/mm/dd - ccyy/mm/dd , so this is what I've come up with and it doesn't seem to work as it should, I think I'm not doing the test right.
List<string> missigDateStrings = new List<string>();
for (int i = 0; i < dateList.Count; i++ )
{
DateTime firstDate = dateList[i];
DateTime secondDate = dateList[i + 1];
if (firstDate.DayOfWeek != DayOfWeek.Saturday &&
firstDate.DayOfWeek != DayOfWeek.Sunday)
{
if (secondDate.DayOfWeek != DayOfWeek.Saturday &&
secondDate.DayOfWeek != DayOfWeek.Sunday)
{
if (firstDate.AddDays(1) != secondDate)
{
string sFirstMissingDate = firstDate.ToShortDateString();
DateTime testDate = firstDate;
while (testDate != secondDate)
{
testDate.AddDays(1);
if (testDate == secondDate)
{
string sLastMissingDate = firstDate.AddDays(1).ToShortDateString();
string range = String.Format("{0}-{1}", sFirstMissingDate, sLastMissingDate);
missigDateStrings.Add(range);
}
}
}
}
}
}
}
Any help would be appreciated.
P.S. all the dates have been converted to DateTime
EXCELLENT ! THANKS ALL
Upvotes: 2
Views: 1317
Reputation: 273864
Change
testDate.AddDays(1);
to
testDate = testDate.AddDays(1);
DateTime is an immutable value-type, AddDays()
returns a new instance but does not (cannot) change the original value.
And just for fun, to answer the title-question,
var missing = Enumerable.Range(0, 10)
.Select(i => baseDate.AddDays(i))
.Except(datesFromFile);
Upvotes: 1
Reputation: 4559
If the gap is longer than 7 days you get weekend days also. I assume that is your problem. So you should add another check for Sat/Sun in
while (testDate != secondDate)
and break the loop on Friday, skip weekend and start loop on Monday again.
EDIT:
Below is always false in your case probably. That's why you don't get any output.
if (firstDate == secondDate)
Upvotes: 1