I am working on a project and writing a function to add two different times. The times are stored in database as a string.
I'm:
Pulling value from db
converting it into time using strtotime
adding times using date function
Here is my code:
$time_1 = '1:00';
$time_2 = '0:05';
//should be 1:05, whereas it prints 04:05
echo date("H:i", strtotime($time_1) + strtotime($time_2));
Please tell me, what is wrong with above code and how it can be fixed?
Thanks
Your problem is because strtotime returns the number of seconds since the Unix Epoch (Jan 1 1970). So what you are getting is not values of 60 and 5, but something more like 1537570800 and 1537567500. When you add those two values together, you end up with a date far in the future, with what looks effectively like a random time. To compensate for this, you need to subtract the value of strtotime at the start of the day to make the second time a relative time e.g.:
echo date("H:i", strtotime($time_1) + strtotime($time_2) - strtotime('00:00'));
Output:
01:05
Update
Since it turns out that the sum of the two times can exceed 24 hours, the above code will not work (the maximum time it will display is 23:59 before rolling over to 00:00. So it is necessary to convert both times to a relative number of minutes to the start of the day, add them and then display as hours and minutes:
$time_1 = '12:00';
$time_2 = '14:30';
$time_sum = (strtotime($time_1) + strtotime($time_2) - 2 * strtotime('00:00')) / 60;
printf('%02d:%02d', intdiv($time_sum, 60), $time_sum % 60);
Output:
26:30
Use DateTime::createFromFormat function, and taking ideas from Adding two DateTime objects in php
$time_1 = '1:00';
$time_2 = '0:05';
$t1 = DateTime::createFromFormat('G:i', $time_1);
$t2 = DateTime::createFromFormat('G:i', $time_2);
$interval1 = $t1->diff(new DateTime('00:00:00')) ;
$interval2 = $t2->diff(new DateTime('00:00:00')) ;
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
Additional Details:
G and H 24-hour format of an hour with or without leading zeros
i Minutes with leading zeros 00 to 59
Related
I'm displaying videos and I want to show the duration. Im using the following:
echo ltrim(date('i:s', $vduration), '0')
//result
5:40
But, if the video is 40 seconds only. The formula doesn't work. It shows
:40
Basically, if the video is less then 60 seconds, it should show 1 zero only (not 2), like so:
0:40
Is there a magic formula for this or do I need to use conditions to check if less or equal to 60 seconds?
Instead of date(), use printf() to format the numbers the way you wan.
$minutes = date('i', $vduration);
$seconds = date('s', $vduration);
printf("%d:%02d", $minutes, $seconds);
%d will format a number with no leading zeroes, %02d will format a number in 2 digits with leading zeroes.
A date is poorly suited to represent a time interval. The DateInterval class is better suited. The date interval format method can also represent minutes without leading zeros.
//example to create a date interval
$timeStart = date_create_from_format('!','');
$timeEnd = date_create_from_format('!i:s','00:07');
$interval = $timeStart->diff($timeEnd);
//output
echo $interval->format('%i:%S'); //0:07
If the minutes and seconds are given, a date interval can also be created directly.
$minute= 1;
$second = 40;
$interval = new DateInterval('PT'.$minute.'M'.$second.'S');
The timestamp in my database is 2015-03-03 00:25:39 (Take note that the type = timestamp and the correct current timestamp in my end is 2015-03-02 01:31:00. The difference should be around 23 hours. But now the problem is that the answers provided in the net will give me 30 hours instead of 23 hours. Some of the codes that I have tried are the following:
$target is the target date
CODE 1:
$then = strtotime($target);
$diff = $then - time();
echo sprintf("%s days and %s hours left", date('z', $diff), date('G', $diff));
But it gives me 1 days and 6 hours left. So 30 hours
CODE2:
$seconds = strtotime("$target") - time();
echo $seconds; exit();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
echo $hours;
It gives me something like 107388 = 30 hours.
CODE 3:
//Convert to date
$datestr= $target;//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
It gives me 6 hours
I don't know what I'm doing wrong, more like I have no idea how to do it.
This is now my last resort since I can't find the solution that will help me.
Hoping for your fast responses.
PHP's DateTime() (and DateInterval()) are much better for date math and returns the correct results:
$date = new DateTime('2015-03-03 00:25:39');
$now = new DateTime('2015-03-02 01:31:00');
$diff = $date->diff($now);
echo $diff->h, ' hours ', $diff->i, ' minutes';
Demo
This is a very late answer, but your question is a good one that will likely be searched for in the future.
Here is an online demo.
// this doesn't appreciate any timezone declarations, you'll need to add this if necessary
$target="2015-03-03 00:25:39"; // declare your input
$then=new DateTime($target); // feed input to DateTime
$now=new DateTime(); // get DateTime for Now
$diff=(array)$then->diff($now); // calculate difference & cast as array
$labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second");
$readable=""; // declare as empty string
// filter the $diff array to only include the desired elements and loop
foreach(array_intersect_key($diff,$labels) as $k=>$v){
if($v>0){ // only add non-zero values to $readable
$readable.=($readable!=""?", ":"")."$v {$labels[$k]}".($v>1?"s":"");
// use comma-space as glue | show value | show unit | pluralize when necessary
}
}
echo "$readable";
// e.g. 2 years, 20 days, 1 hour, 10 minutes, 40 seconds
I have something like that for example: 01:06:22 this represents 1hour, 6minutes and 22seconds. I want to take that, and multiple it by 6 and add it to some other hour such as 04:23 which is 4AM and 23Minutes not 4hours and 23 minutes.
Basically, as a result I expect that:
01:06:22
* 6 = 6hours 38minutes canceling the remaining seconds which are 12 in this case
Now, I want to take that and append it to other hour, 04:23 in this case, so the result would be:
11:01.
I have no clue how to start and do it, unfortunately.
Any help is appriciated!
Clarifications
The time that I have to multiple by 6 will never exceed 2 hours.
All the times are in the same format.
With DateTime it is simple:
$time = '01:06:22';
$dateSeconds = new DateTime("1970-01-01 $time UTC");
$seconds = $dateSeconds->getTimestamp() * 6;
$interval = new DateInterval('PT'.$seconds.'S');
$date = new DateTime('1970-01-01 04:23:00 UTC');
$date->add($interval);
echo $date->format('H:i:s');
Other solution with strtotime and gmdate. (Similar to Suresh but working):
$date = strtotime('1970-01-01 01:06:22 UTC');
$add = strtotime('1970-01-01 04:23:00 UTC');
$date = (($date*6)+$add);
echo gmdate('H:i:s', $date);
This is a solution if you want to implement it yourself.
The thing about timecode is that it can become really heavy with the if the if conditions etc if you don't do it right.
The best Way I thought of to deal with this is to convert everything to second.
so 01:06:22 would become:
numberOfSecond = 22 + 06 * 60 + 01 * 60 * 60
How to get the 22, 06 etc from the String? You can use Regex.
What you will need:
a function to extract the different values (hours, minute, second)
a function to convert the timecode into second
a function to convert back into timecode
the functions to multiply, add etc...
You might want to create a class for it.
You can try like this:
$date = strtotime('01:06:22');
$add = strtotime('00:04:23');
$date = ($date*6)+$add;
echo date('H:i:s', $date);
Note: Code is not tested.
First of all you want to multiply a time span by a factor. The easiest way to do this is to convert the span to seconds and do a straight multiply:
$date =DateTime::createFromFormat('!H:i:s', '01:06:22', new DateTimeZone('UTC'));
$seconds = $date->getTimestamp();
This code works by pretending that the time is a moment during the Unix epoch start so that it can then get the number of seconds elapsed since the epoch (the timestamp). That number is equal to the duration of the time span in seconds. However, it is vitally important that the input is interpreted as UTC time and not as something in your local time zone.
An equivalent way of doing things (as long as the input is in the correct format) which is lower-tech but perhaps less prone to bugs would be
list($h, $m, $s) = explode(':', '01:06:22');
$seconds = $h * 3600 + $m * 60 + $s;
Now the multiplication:
$seconds = $seconds * 6;
If you want to only keep whole minutes from the time you can do so at this stage:
$seconds = $seconds - $seconds % 60;
The final step of adding the result to a given "time" is not clearly specified yet -- does the reference time contain date information? What happens if adding to it goes over 24 hours?
Self explanatory :
$initialTime = '01:06:22';
$timeToAdd = '04:23';
$initialTimeExploded = explode( ':' ,$initialTime );
$initialTimeInMintues = ( $initialTimeExploded[0] * 60 ) + $initialTimeExploded[1];
$initialTimeInMintuesMultipliedBySix = $initialTimeInMintues * 6;
$timeToAddExploded = explode( ':' ,$timeToAdd );
$timeToAddExplodedInMintues = ( $timeToAddExploded[0] * 60 ) + $timeToAddExploded[1];
$newTimeInMinutes = $initialTimeInMintuesMultipliedBySix + $timeToAddExplodedInMintues;
$newTime = floor( $newTimeInMinutes / 60 ) .':' .($newTimeInMinutes % 60);
echo $newTime;
Result :
10:59
I figured this would be a very simple problem but I haven't found a solution anywhere.
I am creating a scheduling program in PHP and mySQL. The shifts have a startTime and endTime, each of which are stored as TIME in mySQL.
I want to add up the total hours for an employee during the week, so I tried:
$shifts = [...] //shifts for the week
$totalTime = 0; //I've also tried "0:0:0" and strtotime("0:00:00");
for($d = 0; $d < 7; $d++){
$start = strtotime($shift_types[$shifts[$d]]['ShiftType']['start_time']);
$end = strtotime($shift_types[$shifts[$d]]['ShiftType']['end_time']);
echo date("g:ia", $start) . ' / ' . date("g:i a", $end);
$totalTime += ($end-$start);
}
}
The problem with this, is that $totalTime doesn't come out to any reasonable number. I think this is because PHP is treating $totalTime as a timestamp since 1970, which would result in something completely different. All I really want is a value of net hours, it doesn't need to have any date-ish values associated with it.
I should mention that I'm displaying the total time with
echo date("g:i", $totalTime);
When it is run with a start of 9:30:00 and an end of 16:15:00, it displays "1:45".
When the total time isn't touched (because there are no shifts), it displays "7:00".
strtotime returns a Unix timestamp, the number of seconds since the epoch represented by that time. So working with seconds (and starting $totalTime at zero) is the correct approach. If you want the number of hours, you need to: $totalTime = $totalTime / (60 * 60); after your loop (divide by 3600 seconds / hour).
I think this does what you want to do:
$t1 = strtotime("2013-01-01 00:00:00");
$t2 = strtotime("2013-01-15 00:00:00");
echo round(($t2-$t1)/3600) ." hours". PHP_EOL;
Or you could look to use two DateTime objects and the diff() method as described in my blog post http://webmonkeyuk.wordpress.com/2011/05/04/working-with-date-and-time-in-php/
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)