计算时间跨度的折扣小时数

时间:2015-09-15 21:26:27

标签: php datetime time

我有一个预订系统,您可以在任意时间预订车辆并按小时付款。晚上10点至早上8点的夜间小时打折。有没有人有一个优雅的解决方案来计算预订的总分钟和折扣分钟,最好是在PHP?

我的初步尝试包括计算整天,并查找全天的全价时间和折扣时间:

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

现在我留下了提醒:

$reminder=fmod($total, 60*60*24);

然而,这是我的麻烦真正开始的地方。我认为有一些方法可以规范时间,这样我就不必拥有多个if / else if,但我不能让它工作:

$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;

这似乎适用于$ time-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; 

有人喜欢破解它吗?

1 个答案:

答案 0 :(得分:0)

我不妨发布我最终如何解决它。优惠期限为2200 - 0800晚。有点失望,我不得不绕过预订,而不是一些我确定存在的更优雅的方法,但这是有效的,我猜是好的。

$interval=30; // allow thirty minutes interval, eg 12:30 - 14:00
$int=$interval*60; // interval in seconds
$twentyfour=24*60*60; // 24 hours in seconds
$eight=8*60*60; // 8 hours in seconds
$twentyto=22*60*60; // 22 hours in seconds

// fraction of a 24-hour period thats discounted
$discount_fraction=10/24; 
$discount=0; // seconds at discount price
$full=0; // seconds at full price
$from=strtotime("2015-09-16 06:00");  //example input
$to=strtotime("2015-09-20 04:00"); //example input
$total=$to-$from; // Total number of seconds booked

// full days booked, in seconds
$full_days=floor($total/60/60/24)*24*60*60; 
// discounted secs within the full days
$discount+=$full_days*$discount_fraction; 
// full price secs within the full days
$full+=(1-$discount_fraction)*$full_days; 

$reminder=fmod($total, 60*60*24); //remaining time less than 24 hours

//start hour of remaining time
$from=date('H',$from)*60*60+date('i',$from)*60+date('s',$from); 

// looping from start-time to start+reminder,
// using the order interval as increment, and 
// starting as start plus 1/2 order-interval
for($i=$from+$int/2; $i<$from+$reminder; $i+=$int){
    if(($i>0 && $i<$eight) || 
        ($i>$twentyto && $i<$twentyfour+$eight) ||
        ($i>$twentyfour+$twentyto)) {
            $discount+=$int; 
    }
    else{
        $full+=$int; 
    }
}
echo "Minutes at discount price ".($discount/60); 
echo "Minutes at full price ".($full/60); 
相关问题