Calculate number of discount hours in timespan - php

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?

I might as well post how I solved it eventually. Discount period from 2200 - 0800 at night. A little disappointed I had to go for looping over the booking instead of some more elegant approach which I'm sure exists, but this works and is good enough I guess.
$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);

Related

how to know the minimum period of week for two date, increasing by different frequence, to overlap

to start im sorry for my bad english and i hope that you can understand my problem and finding a solution for it....
my problem is that i have two period
the first period: dateStart1-dateEnd1
the secondperiod: dateStart2-dateEnd2
for the first couple the frequence = 2 :
dte=dateStar1;dateEnd1>dte;dte+2week
for the second, the frequence = 3 :
dte=dateStar2;dateEnd2>dte;dte+3week
Exemple:
first period 2016-04-04 -> 2016-05-09
frequence 2 weeks 2016-04-04 , 2016-04-18 , 2016-05-02
the second : 2016-04-11 -> 2016-05-09
frequence 3 weeks 2016-04-11, 2016-05-02
the two periods overlaps in 2016-05-02
my question in how to know the minimum number of weeks for the two period or dates to overlaps ?
thank you
There is probably a better algorithm, but the only thing I can think of is a check on all available weeks for a period.
$result = [];
$current = clone $dateStart1;
while ($current < $dateEnd1) {
// Calculate the difference betweenthe current date and dateStart2
$diff = $current->diff($dateStart2);
// Check if the difference is a multiple of the frequency, i.e. if the number of days is congruent to 7 times the frequency
if ($diff->days % ($frequency2 * 7) == 0) {
// If the anwser is yes, adds the current date to the list of overlapping dates.
$result[] = clone $current;
}
// Get the next date possible for period 1 by adding $frequency1 weeks to the current date, and then try again till $dateEnd1 is reached.
$current = $current->add(new \DateInterval('PT'.$frequency1.'W'););
}
return $result;
I haven't fully tested it, but this might at least help you to get on the rails.

Calculate the number of hours in a given timeframe between two datetimes

I have a booking system where users can book a room at any time, and for any number of continuous days. The booking is charged depending on the number of minutes the room is in use.
In the booking system, the start and end time is represented by two timestamps. e.g.
start_time = 1397124000
end_time = 1397129400
From this I can calculate the number of seconds booked, and therefore calculate a charge.
The problem I have is that I'd like to calculate a 50% discount on any bookings made out of peak times - before 8am, and after 6pm. Bookings can be made across these times (i.e. 7am-9am), and so the appropriate proportion should be discounted (50% discount on the 7-8am portion of the 7-9am booking).
My code for calculating this is getting extremely confusing and complicated, as there are several scenarios:
The booking starts and ends during a discount period (e.g. 3am-7am - 4 hours discounted)
The booking starts during a discount, but ends afterwards (e.g. 7am-9am - 1 hour discounted)
The booking starts and ends during a period of non-discount (10am-5pm - no discount)
The booking starts during a period of non-discount, but ends afterwards (5pm-10pm - 1 hour discounted)
The booking spans an entire before-during-after discount period (2am-10pm - 10 hours discounted) or even more complicated (2am on Day 1 to 10pm on Day 5 - 50 hours discounted).
At the moment trying to work out what proportion of a booking is during these pre-8am, post-6pm discount period when only provided with a start and end timestamp is very difficult.
My code is a very large series of if and else statements testing against start and end times, but it is not robust against bookings that span more than one day and is otherwise very messy.
I'm looking for a method that can easily calculate what proportion of a booking is within a discounted time, that accounts for all possible scenarios. A difficult problem!
After pondering many options, the following solution eventually occurred to me.
I wrote a function to move through the booking start and end times in 30 minute intervals, check to see if each time was within a discounted period:
function discount_period($timestamp) {
$lowerTime = mktime (8,0,0,date("n", $timestamp), date("j", $timestamp), date("Y", $timestamp));
$upperTime = mktime (18,0,0,date("n", $timestamp), date("j", $timestamp), date("Y", $timestamp));
if (($timestamp < $lowerTime) || ($timestamp >= $upperTime)) {
return true;
}
else {
return false;
}
}
$discountmins = 0;
$nondiscountmins = 0;
for ($i = strtotime($billingResult->start_time); $i < strtotime($billingResult->end_time); $i += 1800) {
if (discount_period($i)) {
// This is within a discount period of at least 30 minutes
$discountmins += 30;
}
else {
$nondiscountmins +=30;
}
}
$discountedcost = ((($discountmins / 60) * $billingResult->cost_per_hr) * 0.5) / 100;
$nondiscountcost = (($nondiscountmins / 60) * $billingResult->cost_per_hr) / 100;
So it essentially checks to see if the next 30 minute window is within a discount period - if it is, it increments the discounted minute counter, or the non-discounted minute counter if not. At the end it them merely calculates the costs based on the number of minutes.

Extract time frames from time period

I am creating an application that charges a client based on time usage of a service. The problem is that the services can have double charge for a pre-specified time period of the day.
So let's say we have a service for printing documents and the charge for using the printer is 5€ per hour and 10€ between 23:00 and 02:00 in the morning. Also a client can rent the printer for as much time as he likes. This can be from 1 minute to months or even years.
Now the specific problem:
Let's say a client comes in my office to rent the printer for 55 hours. Also the rent starts at 20:00 at night.
So the charge must be for 43 hours in single charge and for 12 hours in double charge. Here are two example images:
Now, let me give you some extra info about the hours. In programming, each hour has a timestamp that it is time passed from January 1, 1970 00:00:00 to the time in seconds.
So the date July 05 2012 11:15:40 has the timestamp 1373022940 and the date July 05 2012 11:15:50 has the timestamp 1373022950
In the above example lets say that the first example placed in the date May 1, 2013, so the timestamp for 23:00 will be 1367449200 and the time stamp for three days later at the 02:00 the morning is 1367546400
Now the question:
Is there a way to extract the time duration of the double charged hours from a time frame? If so, what is the process?
Of course there is. You just need to count the interval between dates.
Let's say someone started using service since 8:00 and ended in 16:00.
Price from 8:00 - 16:00 = 2$
Price from 16:00 - 8:00 = 1$
So you need to convert the start of usage time and end of usage time to timestamp
date_default_timezone_set('UTC');
$day_start = '2011-06-22';
$day_end = '2011-06-22';
$start_usage = strtotime($day_start.' 8:00');
$end_usage = strtotime($day_end.' 17:00');
$price_low_rate = 1; //price for using service 16-8
$price_high_rate = 2; // price for using service since 8-16
$fee_for_eight_sixteen = 0; // total price for using service since 8-16
$fee_for_sixteen_eight = 0; // total price for using service 16-8
if($end_usage >strtotime($day_start.' 16:01'))
{
$fee_for_sixteen_eight = ($end_usage - strtotime($day_end.' 16:00'))/3600 * $price_low_rate;
}
if($start_usage >= strtotime($day_start.' 8:00'))
{
$fee_for_eight_sixteen = (strtotime($day_end.' 16:00') - $start_usage)/3600 * $price_high_rate;
}
echo $fee_for_eight_sixteen.' - '.$fee_for_sixteen_eight;
I've tested it and it works. Hope it helps.
Haven't tested this, but I hope it gets you on the right track:
<?php
$price = 0;
$start_timestamp = 1367449200;
$end_timestamp = 1367546400;
$start_time_of_day = 1367449200 % (24*60*60); // Number of seconds from start of the day
$end_time_of_day = 1367546400 % (24*60*60); // Number of seconds from start of the day
// How much time the time period spends in the first day (in seconds)
$first_day_time = (24*60*60) - $start_time_of_day;
// How much time the time period spends in the last day (in seconds)
$last_day_time = (24*60*60) - $end_time_of_day;
$full_days_time = $end_timestamp + $last_day_time - ($start_timestamp + $first_day_time);
$full_days = round($full_days_time/(24*60*60));
// You can calculate by hand how much one full 24-hour day from 00:00 to 00:00 costs
$price += $full_days * (2*10 + 21*5 + 1*10);
// so now the difficulty is the pieces of time on the first day and the last day.
$expensive_time = 0; // Expensive time spent on the first and last day
$cheap_time = 0;
if ($start_time_of_day<2*60*60)
{
// Renting starts before 02:00
$expensive_time += 2*60*60 - $start_time_of_day;
$cheap_time += 21*60*60; // Full 21 hours of cheap time
$expensive_time += 1*60*60; // 1 hour of expensive time from 23:00 to midnight
}
elseif ($start_time_of_day<23*60*60)
{
// Renting starts after 02:00 and before 23:00
$cheap_time += 23*60*60 - $start_time_of_day;
$expensive_time += 1*60*60; // 1 hour of expensive time from 23:00 to midnight
}
else
{
// Renting starts after 23:00
$expensive_time += 24*60*60 - $start_time_of_day;
}
// !! Use a similar strategy for the $end_time_of_day here
$price += ceil($expensive_time/60/60) * 10;
$price += ceil($cheap_time/60/60) * 5;
echo $price." euro";
?>

Counting the age of an item in weekdays only

I've been trying to count the age of something in weekdays. I've tried the method detailed in this question, Given a date range how to calculate the number of weekends partially or wholly within that range? but it doesn't seem to fit my usecase.
An item has a created DATETIME in the database, and I need to mark it as old if the created date is over 2 days old. However, the client has requested that age only count week days (Mon to Fri) and exclude Sat+Sun.
So far, my pseudo code looks like the following,
now - created_datetime = number_of_days
for(i number_of_days)
if(created_datetime - i)
is a weekday, then age++
There must be a cleaner way of achieving this? As if an item were to get very old, looping through each day of it's age, looking for a weekend day would impact speed quite a bit.
Any ideas would be great! Thanks
You only have to check the last 7 days to know the exact age in weekdays.
Here's the intuition:
Subtract from the total age of the object, the number of weekends in its lifetime. Note that every 7 days there are exactly 2 weekends. Add to this the number of weekend days in the remainder days (the ones that aren't in a full week) and you have to total number of weekend days in its lifetime. Subtract from the real age to get the weekday age.
int weekendCount = 0;
// Check the remainder days that are not in a full week.
for (int i = totalAge % 7; i < 7; i++) {
if (created_datetime - i is weekend) {
weekendCount++;
}
}
weekdayAge = totalNumberOfDays - (((totalNumberOfDays / 7) * 2) + weekendCount);
Note that the division is an integer division.
I'm sure you can do this with some math and a bit of careful thought. You need to check what day of the week the item was created and what day of the week it currently is. First, you calculate the number of days old it is, as I'm sure you were doing at first.
// if today is saturday, subtract 1 from the day. if its sunday, subtract 2
if (now() is sunday) $now = now() - 2 days;
if (now() is saturday) $now = now() - 1 day;
// same thing for $date posted. but adding 1 or 2 days
if ( $date is saturday) $date = $date + 2;
if ( $date is sunday) $date = $date + 1;
// get days difference
$days = $today - $date;
// have to subtract 2 days for every 7
$days = $days - floor($days/7)*2
You'd have to check if that works. Maybe you can do the calculation without moving your date to before/after the weekend. It may not be perfect, but its the right idea. No need to iterate.

Problems adding time

I've run into a strange timewarp while doing some math with time, and it has left me stumped. Or, well, I've found the reason (or atleast a plausible one), but don't quite know what to do about it, or if there is indeed anything that can be done.
The issue in plain words is, that when adding time in larger units than 1 week (it's multipliers excluded) it seems to be impossible to be exact. And by exact I mean, that when I add 1 years worth of seconds to NOW, I end up 1 year and some hours from NOW.
I can understand that adding 1 (or more) months will do this, as a months length varies, but a year should be more or less the same, shouldn't it?
Now I know you'll want to know how I do this, so here follows (pseudoish) code:
class My_DateInterval {
public $length; // Interval length in seconds
public function __construct($interval) {
$this->length = 0;
preg_match(
'/P(((?<years>([0-9]{1,}))Y)|((?<months>([0-9]{1,}))M)|((?<weeks>([0-9]{1,}))W)|((?<days>([0-9]{1,}))D)){0,}(T((?<hours>([0-9]{1,2})){1}H){0,1}((?<minutes>([0-9]{1,2}){1})M){0,1}((?<seconds>([0-9]{1,2}){1})S){0,1}){0,1}/',
$interval, $timeparts
);
if (is_numeric($timeparts['years'])) $this->length += intval($timeparts['years']) * 31556926; // 1 year in seconds
if (is_numeric($timeparts['months'])) $this->length += intval($timeparts['months']) * 2629743.83; // 1 month in seconds
if (is_numeric($timeparts['weeks'])) $this->length += intval($timeparts['weeks']) * 604800; // 1 week in seconds
if (is_numeric($timeparts['days'])) $this->length += intval($timeparts['days']) * 86400; // 1 day in seconds
if (is_numeric($timeparts['hours'])) $this->length += intval($timeparts['hours']) * 3600; // 1 hour in seconds
if (is_numeric($timeparts['minutes'])) $this->length += intval($timeparts['minutes']) * 60; // 1 minute in seconds
if (is_numeric($timeparts['seconds'])) $this->length += intval($timeparts['seconds']);
$this->length = round($this->length);
}
}
class My_DateTime extends DateTime {
public function __construct($time, $tz = null) {
parent::__contruct($time, $tz);
}
public function add(My_DateInterval $i) {
$this->modify($i->length . ' seconds');
}
}
$d = new My_DateTime();
$i = new My_DateInterval('P1Y');
$d->add($i);
Doing some debug printouts of the interval length and before/after values show that it's all good, in the sense that "it works as expected and all checks out", but the issue stated above still stands: there is an anomaly in the exactness of it all which I'd very much would like to get right, if possible.
In so many words: How to do exact mathematics with time units greater than 1 week. (I.e. 1 month / 1 year).
PS. For those wondering why I'm using My_* classes is because PHP 5.3 just isn't widespread enough, but I'm trying to keep things in a way that migrating to built-in utility classes will be as smooth as possible.
A year is 365.25 days, roughly. Hence we have leap years.
Months have variable lengths.
Hence the semantics of what adding a year and adding a month probably don't correspond to adding a fixed number of seconds.
For example adding a month to 14th Feb 2007 would probably be expected to yield 14th March 2007 and to 14th Feb 2008 would ive 14th March 2008, adding 28 or 29 days respectively.
This stuff gets gnarly, especially when we add in different calendars, much of the world doesn't even have a February! Then add "Seven Working Days" - you need to take a public holiday calendar into account.
Are there no libraries you can find for this?
I can understand that adding 1 (or more) months will do this, as a months length varies, but a year should be more or less the same, shouldn't it?
Above, when you're adding a year's worth of seconds, you're starting with the number of days in (what I guess is) and average year (i.e., 365.2421.. * 24 * 60 * 60). So your calculation implicitly defines a year as a certain number of days.
With this definition, December 31 is a little less than 6 hours too long. So your "clock" goes from Dec 31 23:59 to 29:59 (whatever that is) before rolling over to 00:00 on January 1st. Something similar will happen with months, since you're also defining them as a certain number of seconds instead of 28 - 31 days.
If the purpose of your calculation was timing the difference between events on a generic "average" calendar, then your method will work fine. But if you need to have a correspondence with a real calendar, it's going to be off.
The simplest way to do it is to use a fake julian calendar. Keep track of each division of time (year, month, day, etc.). Define days to be 24 hours exactly. Define a year as 365 days. Add 1 day if the year is divisible by 4, but not when it's divisible by 100 unless it's also divisible by 400.
When you want to add or subtract, do the "math" manually ... every time you increment, check for "overflow". If you overflow the day of the month, reset it and increment the month (then check the month for overflow, etc., etc.).
Your calendar will be able to correspond exactly to a real calendar, for almost everything.
Most computer date implementations do basically this (to varying degrees of complexity). In javascript, for example (because my web inspector is handy):
> new Date(2010,0,1,0,0,0) - new Date(2009,0,1,0,0,0)
31536000000
As you can see, that's exactly 365 days worth of milliseconds. No mess, no fuss.
By they way, getting time right is HARD. The math is in base 60. It's all special cases (leap years, daylight savings, time zones).
Have fun.
Just in case someone is interested, the working solution was so simple it (as usual) makes me feel stupid. Instead of translating the interval length into seconds, a wordier version works correctly with PHP internals.
class My_DateInterval {
public $length; // strtotime supported string format
public $years;
public $months;
public $weeks;
public $days;
public $hours;
public $minutes;
public $seconds;
public function __construct($interval) {
$this->length = 0;
preg_match(
'/P(((?<years>([0-9]{1,}))Y)|((?<months>([0-9]{1,}))M)|((?<weeks>([0-9]{1,}))W)|((?<days>([0-9]{1,}))D)){0,}(T((?<hours>([0-9]{1,2})){1}H){0,1}((?<minutes>([0-9]{1,2}){1})M){0,1}((?<seconds>([0-9]{1,2}){1})S){0,1}){0,1}/',
$interval, $timeparts
);
$this->years = intval($timeparts['years']);
$this->months = intval($timeparts['months']);
$this->weeks = intval($timeparts['weeks']);
$this->days = intval($timeparts['days']);
$this->hours = intval($timeparts['hours']);
$this->minutes = intval($timeparts['minutes']);
$this->seconds = intval($timeparts['seconds']);
$length = $this->toString();
}
public function toString() {
if (empty($this->length)) {
$this->length = sprintf('%d years %d months %d weeks %d days %d hours %d minutes %d seconds',
$this->years,
$this->months,
$this->weeks,
$this->days,
$this->hours,
$this->minutes,
$this->seconds
);
}
return $this->length;
}
}

Categories