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

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.

Related

Calculate number of discount hours in timespan

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

Calculating different bands of overtime in php

This is my first time posting here so I'm sorry if I get something wrong. I'm trying to calculate how many hours overtime a worker has worked based on when they signed in. The problem is that we have different bands of overtime:
If the worker works between 5 and 7 then it's 25% extra per hour
If they worked between 7pm and 10pm then its 50% extran for each hour
If the worker works between 10 and 12 then it's 75% extra
If the worker works between 12am and 7am is 100% more
I need to count how many hours they worked at each of the overtime bands
$number_of_25_percent_hours=0;
$number_of_50_percent_hours=0;
$number_of_75_percent_hours=0;
$number_of_100_percent_hours=0;
$clockInTime=$arr['4'];
$clockOutTime=$arr['5'];
$startingPieces=explode(':',$clockInTime);
$startingHour=$startingPieces[0];
$finishingPieces=explode(':',$clockInTime);
$finishingHour=$finishingPieces[0];
//Regular hours are between 7am and and 5pm
//If the worker works between 5 and 7 then it's 25% extra per hour
if(($startingHour<=5)&&($finishingHour>=6)){$number_of_25_percent_hours++;}
if(($startingHour<=6)&&($finishingHour>=7)){$number_of_25_percent_hours++;}
The problem with using the lines above is that it does not work if for example they worked an hour from 6:30 to 7:30.
I'm interested in finding other ways to do this.
you need to store the data more exactly. From your script it looks as if you were only saving the starting hour - which propably is a full number (1,2,3,4 whatsoever)
You script however needs a exact time representation. There are surely many ways to do this but for the sake of a better Script (and as you will propably be able to use some of these more exact values later on) I'd recommend you to store it as a UNIX Timestamp, then get the hour of the Timestamp :
$startingHour = date('H' $timeStampStored)
and check if it's in any of your "bonus" segments. If the user started working at 6:30, the value will hold 6.
This code is completely off the top of my head, untested etc. It's intended as a suggestion of one method you might use to solve the problem, not as a robust example of working code. It uses integers instead of dates, relies on array data being entered in order etc, and probably wouldn't even run.
The basic idea is to set up the scales for each level of overtime multiplier, as well as the hours for non-overtime pay in an array, then loop through that array checking how many hours of each level of overtime have been worked between the inputted times, meanwhile keeping track of a total billable hours value.
$PayMultipliers = array();
$PayMultipliers[0] = array(17,19,1.25);
$PayMultipliers[1] = array(19,22,1.5);
$PayMultipliers[2] = array(22,24,1.75);
$PayMultipliers[3] = array(0,7,1.5);
$PayMultipliers[4] = array(7, 17, 1);
$Start = 3;
$End = 11;
$TotalHours = 0;
for($i = 0; $i <= count($PayMultipliers); $i++)
{
if($Start > $PayMultipliers[$i][0] && $Start < $PayMultipliers[$i][1])
{
$TotalHours += ($PayMultipliers[$i][1] - $Start) * $PayMultipliers[$i][2];
$Start = $PayMultipliers[$i][1];
}
}
echo $TotalHours;
If you want to calculate from 6:30 to 7:30 you'll have to caclulate in minutes, not hours. You can convert the hours and minutes to timestamps, check each time period, and then convert the seconds back to hours.
<?php
$number_of_overtime_hours = array();
$clockInTime = "18:30:00";
$clockOutTime = "19:30:00";
$startingPieces = explode(':',$clockInTime);
$finishingPieces = explode(':',$clockOutTime);
//Timestamps
$startTimestamp = mktime($startingPieces[0],$startingPieces[1],$startingPieces[2]);
$finishTimestamp = mktime($finishingPieces[0],$finishingPieces[1],$finishingPieces[2]);
//finish after 0h
if ($finishTimestamp < $startTimestamp){
$finishTimestamp += 3600 * 24;
}
//set starting and ending points
$overtimePeriods = array(
25 => array (17,19),
50 => array (19,22),
75 => array (22,24),
100 => array (24,31)
);
$overtimeWork = array();
foreach ($overtimePeriods as $key => $val){
//create Timestamps for overtime periods
$beginTimestamp = mktime($val[0],0,0);
$endTimestamp = mktime($val[1],0,0);
//calculate hours inside the given period
$overtimeWork[$key] = (min($finishTimestamp,$endTimestamp) - max($startTimestamp,$beginTimestamp)) / 3600;
//negative values mean zero work in this period
if ($overtimeWork[$key] < 0) $overtimeWork[$key] = 0;
}
var_dump($overtimeWork);

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