Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days in date range, excluding weekends and other dates, in C#

Tags:

date

c#

I have a C# method like this:

public static int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, String excludeDates)
{
}

What it's supposed to do is calculate the number of days between the startDate and endDate, but optionally needs to exclude weekends and also other dates (passed in as a comma-separated string of dates).

I have absolutely no idea how to tackle this. My gut instinct would be to loop from startDate to endDate and do some string comparisons, but from what I can find out, C# doesn't allow looping through dates in that way - or at least it's not a very elegant way of doing things.

like image 666
Dan Avatar asked Jun 30 '11 16:06

Dan


People also ask

How do you calculate days excluding weekends?

Add business days excluding weekends with formula To add days excluding weekends, you can do as below: Select a blank cell and type this formula =WORKDAY(A2,B2), and press Enter key to get result. Tip: In the formula, A2 is the start date, B2 is the days you want to add.


1 Answers

Oh it's really easy to loop through the dates - that's not a problem at all:

// I'm assuming you want <= to give an *inclusive* end date...
for (DateTime date = start; date <= end; date = date.AddDays(1))
{
     // Do stuff with date
}

You could easily write an IEnumerable<DateTime> too, and use foreach.

I'd try to avoid doing string operations here if possible though - fundamentally these dates aren't strings, so if you can work in the problem domain as far as possible, it'll make things easier.

Of course there may well be more efficient ways than looping, but they'll be harder to get right. If the loop is okay in terms of performance, I'd stick to that.

As a quick plug for my own open source project, Noda Time has a rather more diverse set of types representing dates and times - in this case you'd use LocalDate. That way you don't have to worry about what happens if the time in "start" is later than the time in "end" etc. On the other hand, Noda Time isn't really finished yet... the bits you need for this are ready and should work fine, but it's possible the API could still change in the future.

EDIT: If you do need to loop through dates frequently, you might want something like this extension method (put it in a top-level non-generic static class):

public static IEnumerable<DateTime> To(this DateTime start, DateTime end)
{
    Date endDate = end.Date;
    for (DateTime date = start.Date; date <= endDate; date = date.AddDays(1))
    {
        yield return date;            
    }
}

Then:

foreach (DateTime date in start.To(end))
{
    ...
}
like image 117
Jon Skeet Avatar answered Nov 15 '22 21:11

Jon Skeet