Reputation: 51063
I have a CSV file that I import into a VehicleMovement
table. Each record is either a vehicle exit or entrance to a parkade, and after jumping through hoops while on fire, I have consolidated these into a VehiclePresence
table, where nearly each record has both a StartDateTime
and EndDateTime
. Now I must calculate the parking charge for the length of the vehicle's presence. This is a problem when the presence spans more than one day. Parking prices are based on time of day, day of week, etc. so I need to split that presence into single day presences and calculate daily charges on them.
E.g. I have a cutover time of 06h00, and a VehiclePresence
record where StartDateTime
== 2013-04-22 20:37:28 and EndDateTime
== 2013-04-25 22:55:20. I would like to conjure up the following VehiclePresenses
:
1. 04/22 20h37 to 04/23 06h00.
2. 04/23 06h00 to 04/24 06h00.
3. 04/24 06h00 to 04/25 22h55.
This will leave me with one original VehiclePresence
record with modified start and end times, and two new records I will insert. This poses no problem.
How can I do this? I would personally just have one huge charge for over 24 hours, but I'm briefed to allow for all kinds of pricing rules.
Upvotes: 1
Views: 947
Reputation: 700222
Calculate the first break time after the start time, and loop day after day until you reach the end time.
Example:
DateTime StartDateTime = new DateTime(2013, 04, 22, 20, 37, 28);
DateTime EndDateTime = new DateTime(2013, 04, 25, 22, 55, 20);
DateTime startTime = StartDateTime;
// calculate first break time
DateTime breakTime = StartDateTime.Date.AddHours(6);
if (breakTime < StartDateTime) {
breakTime = breakTime.AddDays(1);
}
while (breakTime < EndDateTime) {
Console.WriteLine("{0} - {1}", startTime, breakTime);
// move to next day
startTime = breakTime;
breakTime = breakTime.AddDays(1);
}
Console.WriteLine("{0} - {1}", startTime, EndDateTime);
Output:
2013-04-22 20:37:28 - 2013-04-23 06:00:00
2013-04-23 06:00:00 - 2013-04-24 06:00:00
2013-04-24 06:00:00 - 2013-04-25 06:00:00
2013-04-25 06:00:00 - 2013-04-25 22:55:20
Upvotes: 1