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);
Related
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
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'));
I'm trying to get remaining Days, hours and minutes to a certain date using php.
However i get a very strange output from my code which looks like this:
-16828 days and -11 hours and -21 minutes and -24 seconds
The future dates are stored in the mysql database in this format:
29/01/2016 7pm
So I went ahead and done this:
$Draw_time = "29/01/2016 7pm";
$date = $Draw_time;
$timestamp = strtotime($date);
$new_date = date('Y-m-d a',$timestamp );
$seconds = strtotime($new_date) - time();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
echo "$days days and $hours hours and $minutes minutes and $seconds seconds";
But when i run this code, I get the above strange output!
I understand that this could be because of a number reasons but the only thing i could think of is the fact that I am using a in my format?
Could someone please advise on this issue?
Simply use DateTime class like as
$Draw_time = "29/01/2016 7pm";
$date = DateTime::createFromFormat("d/m/Y ha",$Draw_time);
$date2 = new DateTime();
echo $diff = $date2->diff($date)->format("%a days and %H hours and %i minutes and %s seconds");
Try this
<?php
$Draw_time = str_replace('/', '-', "29/01/2016 7pm");
$now = new DateTime();
$futureDate = new DateTime($Draw_time);
$interval = $futureDate->diff($now);
echo $interval->format("%a days %h hours %i minutes %s seconds");
?>
Try this.
$draw_time = "2016/01/29 7pm";
$date_time = explode(" ", $draw_time);// make separate date and time in array
$date = strtotime($date_time[0]); // convert your date(2016/01/29) into php time
$time = strtotime($date_time[1]); // convert your time(7pm) into php time
$date = $date + $time; // make total time to count
$new_Date = $date - (time()); // convert into difference from current time
$day = $new_Date % 86400;
$hrs = $new_Date % 3600;
$min = $new_Date % 60;
echo "Day= ".(date("d",$day));
echo " Hours= ".(date("h",$hrs));
echo " Minutes= ".(date("i",$min));
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]
The future time is :2012-05-26 00:00:00
supposed there are three variable: $hour $minute $second
now, i want to using the future time subtract now time. then give the left hour to $hour,give the left minute to $minute,give the left second to $second.
i am sorry i am new of php, now i get stucked how to do the math operation ? thank you
A very good resource for dates and time..
http://www.php.net/manual/en/function.time.php
-there are samples here doing something similar.
Check the date_diff function. There's the exact solution to what you're asking there.
And here's the page (DateInterval::format) documenting how you can format the output.
$now = date_create();
// use "now" and necessary DateTimeZone in the arguments
$otherDate = date_create('2020-04-13');
$interval = date_diff($now, $futureDate);
echo $interval->format('%a days');
The following are the math operations for the difference in hours,minutes and seconds
$future_datetime = '2012-05-26 00:00:00';
$future = strtotime($future_datetime); //future datetime in seconds
$now_datetime = date('Y-m-d H:i:s');
$now = date('U'); //now datetime in seconds
//The math for calculating the difference in hours, minutes and seconds
$difference = $future - $now;
$second = 1;
$minute = 60 * $second;
$hour = 60 * $minute;
$difference_hours = floor($difference/$hour);
$remainder = $difference - ($difference_hours * $hour);
$difference_minutes = floor($remainder/$minute);
$remainder = $remainder - ($difference_minutes * $minute);
$difference_seconds = $remainder;
echo "The difference between $future_datetime and $now_datetime is $difference_hours hours, $difference_minutes minutes and $difference_seconds seconds";