Calculate time difference with formatted time - php

I have two times: a starting time and the duration. I want to subtract the duration from the starting time. The time I read from an mysql db and is already formatted. My code:
$start= $row["start"]; //output is for e.g. 08:00:00
$dur = $row["duration"]; //output is for e.g. 01:00:00
$sub = $start - $dur;
// I want the output to be 07:00:00
// the result now is 7 and I got an error (non well formed numeric value)
Can someone help me?

Alternatively you can achieved like this
$date = "1970-01-01";
$start = $date." ".$row["start"];
$dur = $date ." ".$row["duration"];
$date1=date_create($start);
$date2=date_create($dur);
$diff=date_diff($date1,$date2);
echo $diff->format("%H:%I:%S");

$start= "08:00:00";
$dur = "01:00:00";
$diff = differenceInHours($start, $dur);
echo convertTime($diff);
function differenceInHours($startdate,$enddate){
$starttimestamp = strtotime($startdate);
$endtimestamp = strtotime($enddate);
$difference = abs($endtimestamp - $starttimestamp)/3600;
return $difference;
}
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}

You should always save date in your database in the appropriate format. And not as a "already formated" value. Except in very specific case.
Anyway, to solve your problem you can do soemthing like this
$start = new DateTime('08:00:00');
$duration = new DateTime('01:00:00');
$interval = date_diff($start, $duration);
echo $interval->format('%H:%I:%S'); //ouput will be 07:00:00

Related

Add fractional hours to a DateTime in php

I have a system which I need to add a certain amount of fractional hours.
I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = array();
$time = explode(".", $hours);
$time [1] += $time [0]*60;
$now->modify("+".$time[1]." hours");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');
The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead
Adding the hours is not correct. When you multiply hours times 60 it will make minutes.
This code should work.
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = explode(".", $hours);
$time[1] += $time[0]*60;
$now->modify("+".$time[1]." minutes");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');
Result is 2017-10-30 09:46:00
You should use DateInterval php class to create an inverval with x seconds from your $hours variable.
Then you just have to use the datetime add interval method to modify your date
Please take a look a this example
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
var_dump($now);
$timeParts = explode(".", $hours);
// Where 23 is a percentage of on hour
$minutes = $timeParts[0] * 60 + round($time[1] * 60 / 100);
// Where 23 is the number of minutes
$minutes = $timeParts[0] * 60 + $time[1];
$interval = new DateInterval(sprintf('PT%dM', $minutes));
$now->add($interval);
echo $now->format('Y-m-d H:i:s');
return $now;
}
Use date_add
date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));
or as object:
$now->add( DateInterval::createFromDateString($tempo[1].' hours'));

Add up time from DateTime in PHP

I'll try to explain my problem. I am beginner with PHP and need help manipulating Date/Time.
So here is my situation.
I get Date/Time values from the database in this format: 07/02/2017 11:00 pm
First I need to calculate a difference between two dates and output duration.
Then add up duration and output total time.
The code is very dirty as I am just researching now. I also came to a problem that DateTime does no carry over points. As far as understand I need to convert days to hours and add them up.
Can anybody more experienced make sense of this?
$total_time = new DateTime('00:00');
$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');
$interval = $start_date->diff($end_date);
$total_days = $interval->days;
$hours = $interval->h;
if ($total_days !== FALSE) {
$hours += 24 * $total_days;
}
$minutes = $interval->i;
$total_time ->add($interval);
echo $hours .'hours ' . $minutes . 'minutes';
echo $total_time->format('h:i'); ?>
You can add a DateInterval to the DateTime.
You can check on http://php.net/manual/en/datetime.add.php
Looking at your code:
$total_hours = 0;
$total_minutes = 0;
//must be initialized outside of the while loop
$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');
$interval = $start_date->diff($end_date);
$hours = $interval->h + 24*$interval->d; /*there is no need to check
if you have total days, since 0 days would still work as expected */
$minutes = $interval->i;
echo 'Duration: '.$hours.' hours '.$minutes.' minutes';
$total_hours += $hours;
if(($total_minutes += $minutes) >= 60) {
$total_hours += 1;
$total_minutes -= 60;
}
//after the end of the while loop
echo 'Total time:'.$total_hours.':'.$total_minutes;
Now I don't understand what is the expected output of total time, if you can elaborate on what is not working it would be easier to help

Getting wrong time after subtraction

Hello I am using strtotime function to subtract time but I am not able to getting such true value of it.
$time = strtotime('00:00:00');
$time1 = strtotime('23:00:00');
$t = $time - $time1;
echo "diff".$t1 = date('H:i:s',$t);
But am getting $t = 2:00:00 Instead of i get 1:00:00
Any one have idea whats gone wrong ?
try to add strtotime() on changing format
date('H:i:s',strtotime($t));
$time = strtotime('00:10:00');
$time1 = strtotime('23:00:00');
$t = $time - $time1;
$hours = floor(($t - (($t/ 86400)* 86400)) / 3600);
$minutes = floor(($t - (($t/ 86400) * 86400) - ($hours * 3600))/60);
echo "".$hours.':'.$minutes;
its give you right diff. time for same days .

Php's new DateTime() is not working on my new server

I am trying to calculate the time interval between two Dates. So here is my code
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
when i try to echo the result it returns an empty result.
This same code worked on my development server and localhost, As soon as i changed to another server it stoped responding.
I checked php.ini for timezone setting, it was good.
I will be thank full for your help
Check your php.ini files inside /etc/php5/apache2/ and /etc/php5/cli/ folders. Both files must have declared the default time zone eg. date.timezone = "America/New_York"
Other way you can have it to work is declaring it inside your code before creating the DateTime object
date_default_timezone_set('America/New_York');
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
NOTE: I suggest that you store everything in timestamp in your database rather than in date. And in your display logic, convert it to date, or find how old it is, etc. Read this on Datetime vs timestamp Should I use field 'datetime' or 'timestamp'?
Below,find two functions to find time difference between two timestamps as well as get the age of an old timestamp compared to now.
<?php
echo whatAge(#SOME TIMESTAMP HERE#)
echo getDiff(#TIMESTAMP1, TIMESTAMP2#)
?>
This gives you day hour minute second. Modify the secondsToTime function below for something else.
Use the functions below...
function whatAge($old_time){
$current_time = getdate(time())[0];
$time_diff = $current_time-$old_time;
return secondsToTime($time_diff,'string');
}
function getDiff($time1, $time2){
$time_diff = $time1-$time2;
return secondsToTime($time_diff,'string');
}
function secondsToTime($inputSeconds, $return='array') {
/** https://stackoverflow.com/questions/8273804/convert-seconds-into-days-hours-minutes-and-seconds */
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
$str = function($d,$h,$m,$s){
if($d>0){
return "$d d, $h h $m m";
}else{
return "$h h $m m";
}
};
switch ($return){
case 'array' : return $obj; break;
case 'string' : return $str($obj['d'],$obj['h'],$obj['m'],$obj['s']); break;
}
}
Simple Way
Try this:
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
read more [php DateTime::diff manual][1]

Add hours which are in G:i format php

I currently have a list of time diffs in G:i format.
I would like to add them all up but when i try to it resets at 24 back to 0.
How can i get a result like: 54:45 for example?
Thanks in advance.
date_default_timezone_set('UTC');
$username = $row['username'];
$begintime = $row['begintime'];
$endtime = $row['endtime'];
$begintime = new DateTime($begintime);
$begintime = $begintime->format('H:i');
$endtime = new DateTime($endtime);
$endtime = $endtime->format('H:i');
$difference = strtotime($endtime) - strtotime($begintime);
$difference = date('G:i', $total);
$total_hours += $difference;
Don't use date() to format absolute times. Since $difference contains the time difference in seconds, it's just a matter of simple arithmetics:
$hours = floor( $difference / 60 / 60 );
$minutes = ( $difference / 60 ) % 60;
echo "$hours:$minutes";
You can actually "trick" DateTime into doing absolute times by adding the differences to an arbitrary date:
$foo = new DateTime();
$bar = new DateTime();
foreach ($intervals as $interval) {
$begin = $interval['begin'];
$end = $interval['end'];
$foo->add($begin->diff($end));
}
// Will be the total time of all intervals, as an interval itself
$total = $foo->diff($bar);

Categories