I have a booking system where you can book a car for an arbitrary time and pay by the hour. Nighttime hours between 10pm and 8am are discounted. Does anyone have an elegant solution for calculating total minutes and discounted minutes for a booking, preferably in php?
My initial attempt includes calculating the full days, and finding the full price time and discount time for full days:
date_default_timezone_set('Europe/Oslo');
$discount_fraction=10/24;
$discount=0;
$full=0;
$from=strtotime("2015-09-16 12:00"); $to=strtotime("2015-09-20 14:00"); //example
$total=$to-$from; // seconds
$full_days=floor($total/60/60/24)*24*60*60; // seconds
$discount+=$full_days*$discount_fraction; // discounted seconds
$full+=(1-$discount_fraction)*$full_days; // full price seconds
Now I'm left with the reminder:
$reminder=fmod($total, 60*60*24);
However, this is where my troubles really start. I'm thinking there is some way to normalize the times so that I dont have to have more than a few if/else if's, but I cant make it work:
$from=date('H',$from)*60*60+date('i',$from)*60+date('s',$from); // seconds
$to=$reminder; // seconds
$twentyfour=24*60*60; // useful values
$fourteen=14*60*60;
$ten=10*60*60;
$eight=8*60*60;
$twentyto=22*60*60;
This seems to work when $from-time < 8:
$d=0;
$f=0;
if($to<=($eight-$from)) $d=$reminder;
else if($to<=$twentyto-$from){
$d=$eight-$from;
$f=$to-($eight-$from);
}
else if($to<$eight+$twentyfour-$from){
$f=$fourteen;
$d=$to-$fourteen;
}
else if($to<$twentyto+$twentyfour-$from){
$d=$ten;
$f=$to-$ten;
}
$discount+=$d;
$full+=$f;
Anyone like to take a crack at it?