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;
}
}
Related
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.
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);
I wrote the following code to determine the amount of time that employees spend on a task:
$time1 = $row_TicketRS['OpenTime'];
$time2= $row_TicketRS['CloseTime'];
$t1=strtotime($time1);
$t2=strtotime($time2);
$end=strtotime(143000); //143000 is reference to 14:30
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
The above code is not giving me the correct time.
For example, with a start time of 09:19:00 and end time of 11:01:00 it give me duration time of only 1 hour which is wrong. What is the correct way?
Your use of floor is why you are getting only 1 hour for those inputs. Those inputs result in 1.7 hours if you keep the answer as a float. floor automatically rounds down to the lower integer value. Check out http://php.net/manual/en/function.floor.php for more info.
$t1 = strtotime('09:19:00');
$t2 = strtotime('11:01:00');
$hours = ($t2 - $t1)/3600; //$hours = 1.7
If you want a more fine-grained time difference, you can flesh it out...
echo floor($hours) . ':' . ( ($hours-floor($hours)) * 60 ); // Outputs "1:42"
UPDATE:
I just noted your comments on Long Ears' answer. Please check my comments above again, they are correct. Inputting values of '09:11:00' and '09:33:00' results in 0 hours (22 minutes).
If you input those values and got 4 hours, you likely have a decimal error in your math. Using '09:11' to '09:33', the result is .367 hours. If you divided the strtotime results by 360 instead of by 3600, you would get result 3.67 hours (or 4 hours, depending on your rounding method).
strtotime converts your time to an int value representing number of seconds since Unix epoch. Since you convert both values to seconds, and then subtract the values from each other, the resulting value is a quantity of seconds. There are 3600 seconds in 1 hour.
After changing strtotime('14:30:00') everything working fine.. see below
$time1 = '09:19:00';
$time2= '11:01:00';
echo "Time1:".$t1=strtotime($time1);
echo "<br/>Time2:".$t2=strtotime($time2);
echo "<br/>End:".$end=strtotime('14:30:00');
echo "<br/>Floor value:";
var_dump(floor((($end- $t1)/60)/60));
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
function getTimeDiff($dtime,$atime)
{
$nextDay=$dtime>$atime?1:0;
$dep=explode(':',$dtime);
$arr=explode(':',$atime);
$diff=abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
//Hour
$hours=floor($diff/(60*60));
//Minute
$mins=floor(($diff-($hours*60*60))/(60));
//Second
$secs=floor(($diff-(($hours*60*60)+($mins*60))));
if(strlen($hours)<2)
{
$hours="0".$hours;
}
if(strlen($mins)<2)
{
$mins="0".$mins;
}
if(strlen($secs)<2)
{
$secs="0".$secs;
}
return $hours.':'.$mins.':'.$secs;
}
echo getTimeDiff("23:30","01:30");
A better way is to use http://php.net/manual/en/datetime.diff.php
$start_t = new DateTime($start_time);
$current_t = new DateTime($current_time);
$difference = $start_t ->diff($current_t );
$return_time = $difference ->format('%H:%I:%S');
for example the start time is 09:19:00 and end time is 11:01:00 but it give me duration time only 1 hour which is wrong
You are calculating the difference in hours. what is the correct result for "start time is 09:19:00 and end time is 11:01:00"
You need strtotime('14:30') rather than strtotime(143000)
Edit: Actually to my surprise, strtotime(143000) does seem to have the desired effect but only for double-digit hours so I still wouldn't rely on it. Anyway it's not the cause of your problem ;)
You can use $hour = ($end - $t1)/(60*60)
In this the time format is (seconds*minutes*days*months*years) => (60*60*2)
How would you go about calculating the amount of months between two arbitrary dates? Given that even if just one day falls on a month, it is considered a full month.
Examples:
2010-01-01 - 2010-03-31 = three months
2010-06-15 - 2010-09-01 = four months
Et cetera. I thought of just dividing the difference of timestamps with 2592000 (average number of seconds in a month) but that seems hacky and prone to errors. And I'd like to keep it as fast as possible (needs to run thousands of times quick), so I guess using strtotime isn't optimal either?
If I am reading your question correctly, you would want to return "2" for January 31st and February 1st, because it spans both January and February, even though they are only 1 day apart.
You could work out (psuedocode):
monthno1 = (date1_year * 12) + date1_month;
monthno2 = (date2_year * 12) + date2_month;
return (monthno2 - monthno1) + 1;
This assumes that the second date is the later date.
Assuming the dates are in a known format:
function getMonths($start, $end) {
$startParsed = date_parse_from_format('Y-m-d', $start);
$startMonth = $startParsed['month'];
$startYear = $startParsed['year'];
$endParsed = date_parse_from_format('Y-m-d', $end);
$endMonth = $endParsed['month'];
$endYear = $endParsed['year'];
return ($endYear - $startYear) * 12 + ($endMonth - $startMonth) + 1;
}
This gives:
print(getMonths('2010-01-01', '2010-03-31')); // 3
print(getMonths('2010-06-15', '2010-09-01')); // 4
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.