Just wondering if there is a more optimized and/or neater way (using LINQ for example) of writing what I have below to get a list of business week date ranges between two dates?
This is what I have currently ..
// Some storage
public class Bucket
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
// Other code removed for brevity ...
DateTime start = new DateTime(2015, 7, 1);
DateTime end = new DateTime(2015, 9, 1);
DayOfWeek firstDayOfWeek = DayOfWeek.Monday;
DayOfWeek lastDayOfWeek = DayOfWeek.Friday;
var buckets = new List<Bucket>();
var currentDate = start;
DateTime startOfBucket = currentDate;
DateTime endOfBucket = currentDate;
while (currentDate <= end)
{
var currentDayOfWeek = currentDate.DayOfWeek;
// Skip days outside the business week
if (currentDayOfWeek >= firstDayOfWeek && currentDayOfWeek <= lastDayOfWeek)
{
if (currentDayOfWeek == firstDayOfWeek)
{
// Start a new bucket
startOfBucket = currentDate;
}
if ((currentDayOfWeek == lastDayOfWeek) || (currentDate == end))
{
// End of bucket
endOfBucket = currentDate;
// Create bucket
buckets.Add(new Bucket()
{
StartDate = startOfBucket,
EndDate = endOfBucket
});
}
}
currentDate = currentDate.AddDays(1);
}
And this will give me the following date ranges ...
- Start: 01/Jul/2015 End: 03/Jul/2015
- Start: 06/Jul/2015 End: 10/Jul/2015
- Start: 13/Jul/2015 End: 17/Jul/2015
- Start: 20/Jul/2015 End: 24/Jul/2015
- Start: 27/Jul/2015 End: 31/Jul/2015
- Start: 03/Aug/2015 End: 07/Aug/2015
- Start: 10/Aug/2015 End: 14/Aug/2015
- Start: 17/Aug/2015 End: 21/Aug/2015
- Start: 24/Aug/2015 End: 28/Aug/2015
- Start: 31/Aug/2015 End: 01/Sep/2015
N.B. The first and last weeks are purposefully not full weeks (they abide to the date range given).
Edit The solution provided here gives the number of days between the two dates but I am interested in getting the collection of date ranges.
Also, I don't need to account for any holidays.
Thanks,