开发者

How do I get the missing dates from a range

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


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)


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);  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜