k1dev
k1dev

Reputation: 641

Number of days for a given year inside a date range

Say I have an year, 2017.

I then have a date range, 01/07/2017 - 01-07-2018 OR 01/07/2017 - 01-01-2017 OR 01/01/2016 - 01/01/2018 ( <- this should return 365 days)

I now need to calculate how many total days are there in the given range for the given year.

Note that dates are stored as dd/mm/yyyy with an always 00:00:00 time.

What would the best logic be considering all possible cases of ranges?

Upvotes: 1

Views: 432

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239636

You can compute the start and end dates for a year easily:

var start2017 = new DateTime(2017,1,1);
var end2017 = new DateTime(2017,12,31);

And then you can compute the overlap between this new range and your other range1:

var startOverlap = start2017 < startOtherRange ? startOtherRange : start2017;
var endOverlap = end2017 >  endOtherRange ? endOtherRange : end2017;

var totalDays = (endOverlap - startOverlap).TotalDays + 1;

The above is correct if ranges are meant to include both their start and end dates. If you want, say, an exclusive endpoint then we'd adjust the end of out 2017 computed range one day further forwards and would no longer require the +1 adjustment at the end)

(And I presume you can derive from there how to turn it into a function if required that takes year, startRange, endRange parameters and does the above with some appropriate renaming)


1I had some vague recollection of DateTime.Min(value1, value2) and similarly for Max but it's definitely not in the BCL that I can see. Those would replace the conditional operators on the following lines. Once C# has "extension everything" these functions could be written as static extensions to DateTime.

Upvotes: 8

Related Questions