Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of inclusive dates covered by a date period

Tags:

date

c#

datetime

I'm looking to count the number of dates covered (inclusive) between two DateTimes.

This is not .TotalDays as periods less than 24 hours may still return "2" by overlapping two different days. Likewise, two dates minutes apart should still return "1".

For example:

2012-2-1 14:00 to 2012-2-2 23:00 -> 2 (1st and 2nd Feb)
2012-2-1 14:00 to 2012-2-2 10:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-2 00:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-3 00:00 -> 3 (1st, 2nd, 3rd Feb)
2012-2-1 14:00 to 2012-2-1 15:00 -> 1 (1st Feb)
2012-2-1 14:00 to 2012-2-1 14:00 -> 1 (1st Feb)
2012-1-1 00:00 to 2012-12-31 23:59 -> 366 (All of 2012)

I can get this functionality with the code below:

DateTime dt1 = new DateTime(2000,1,2,12,00,00);
DateTime dt2 = new DateTime(2000,1,3,03,00,00);

int count = 0;
for (DateTime date = dt1; date.Date <= dt2.Date; date = date.AddDays(1))
    count++;

return count;

Is there a better way?

like image 981
Matt Mitchell Avatar asked Dec 20 '12 10:12

Matt Mitchell


People also ask

Does between two dates include the dates?

Yes it includes start and end date and you could easily find this in the documentation.

How do you count the number of days?

To count days: Assign each day of the week a value between 1 and 7. If your days occur within the same week, subtract the earlier date from the later date. If your days occur in different weeks, add 7 to the later date for each week of difference, and then do the same subtraction.

How do I calculate the number of days between two dates?

To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.

Do you include end date in calculation?

When calculating timelines, the day the event occurred is not counted. The next day is counted as day one and the last day of the event is included in the count.


1 Answers

Why not just:

int count = dt1.Date.Subtract(dt2.Date).Duration().Days + 1;

Using .Date normalizes the Date to midnight (0:00), add 1 to the Days to get the number of different dates, not just the number of days in between.

Using Duration makes sure you always get a positive answer.

like image 86
Davio Avatar answered Oct 03 '22 15:10

Davio