I have a data structure like this which holds start/end dates:
----|-----------|-----------
Item| start | end
----|-----------|-----------
1 |2017-05-12 | 2017-05-12
2 |2017-05-12 | 2017-05-13
3 |2017-05-13 | 2017-05-13
4 |2017-05-13 | 2017-05-14
5 |2017-05-14 | 2017-05-15
6 |2017-05-15 | 2017-05-16
7 |2017-05-16 | 2017-05-16
I want to move the start date of the first item to 2017-01-01 and every item should follow that start date and must stay within its ranges. The result should look like the following:
----|-----------|-----------
Item| start | end
----|-----------|-----------
1 |2017-01-01 | 2017-01-01
2 |2017-01-01 | 2017-01-02
3 |2017-01-02 | 2017-01-02
4 |2017-01-02 | 2017-01-03
5 |2017-01-03 | 2017-01-04
6 |2017-01-04 | 2017-01-05
7 |2017-01-05 | 2017-01-05
This is how I implemented the method:
// ActiveItems() method (although it's bad naming) retrieves all the currently active hotels/transfers etc from a booking.
var items = booking.ActiveItems(); // each item has check-in and/or check-out dates, internals doesn't matter for this problem
var tempCurrentDate = newStartDate;
var previousCheckoutDate = newStartDate;
// go thru each item
for (var i = 0; i < items.Count; i++)
{
var currentItem = items[i];
// again, bad naming but internals doesn't really matter. method returns a check-in date (DateTime)
var itemCheckinDate = currentItem.CheckInDate();
var itemCheckoutDate = currentItem.CheckOutDate();
// no of days between check-out and check-in
// this difference later added to the new check-in date to get the new check-out
var checkinToCheckoutDifference = (itemCheckoutDate - itemCheckinDate).Days;
if (i == 0)
{
// check-in equals to start date if the item is the first one in the list
itemCheckinDate = tempCurrentDate;
}
else
{
var prevDayToCurrentCheckinDifference = (previousCheckoutDate - currentItem.CheckInDate()).Days;
itemCheckinDate = tempCurrentDate.AddDays(prevDayToCurrentCheckinDifference);
}
//SetCheckInDate() internals really doesn't matter here.
currentItem.SetCheckInDate(itemCheckinDate);
previousCheckoutDate = itemCheckoutDate;
tempCurrentDate = itemCheckinDate.AddDays(checkinToCheckoutDifference);
currentItem.SetCheckOutDate(tempCurrentDate);
}
Even though this code works as expected, is there a better and efficient way of doing this?
monospace
, which led me to believe that the table was misaligned ... \$\endgroup\$