HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Adjusting dates in an array based on a start date

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayadjustingdatesdatebasedstart

Problem

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

Even though this code works as expected, is there a better and efficient way of doing this?

Solution

var items = booking.ActiveItems(); // each item has check-in and/or check-out dates

var offset = items[0].GetCheckInDate().Date - DateTime.Parse("2017-05-12");

foreach(var item in items)
{
   item.SetCheckInDate(item.GetCheckInDate() - offset);
   item.SetCheckOutDate(item.GetCheckOutDate() - offset);
}


That, however would not account for e.g. holidays, weekends, availability

And the only reason to do iterative adjustmens (as in original code) would be if SetDate would automatically make adjustments to holidays/weekends inside.

In this case original code lacks comments around that area explaining that SetDate might change the date by itself and absolute day offset would change.

Code Snippets

var items = booking.ActiveItems(); // each item has check-in and/or check-out dates

var offset = items[0].GetCheckInDate().Date - DateTime.Parse("2017-05-12");

foreach(var item in items)
{
   item.SetCheckInDate(item.GetCheckInDate() - offset);
   item.SetCheckOutDate(item.GetCheckOutDate() - offset);
}

Context

StackExchange Code Review Q#153380, answer score: 3

Revisions (0)

No revisions yet.