finding hour difference between two times in php not working - php

I have 2 times in my sql table like 02:56:07pm and 03:56:14pm, so i converted it like:
$time1 = date("G:i:s", strtotime($row['timein']));
$time2 = date("G:i:s", strtotime($row['timeout']));
which gives me two times like 14:56:07 and 15:56:14
now am trying to find the difference in hours between this two times and I did like below:
$difference = round(abs($time2 - $time1) / 3600,2);
echo $difference;
but here am getting 0 as answer

This works for me:
Using strtotime that converts a date/time string into a Unix Timestamp (eg. 163612416703). Now calculations can be done on the times.
$time1 = strtotime('02:56:07pm');
$time2 = strtotime('05:56:14pm');
$difference = date('H:i:s', ($time2 - $time1));
echo $difference; //03:00:07
Play around with the formatting etc..

Related

PHP: Wrong Time Calculation

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

Calculating time difference between two 24H time in php

I'm struggling to calculate time difference between two 24 hour format. The data extracted from my database is like this:
$timein = "09:00";
$timeout = "17:00";
$timediff = $timein - $timeout
As above, how do I get the $timediff = 8?
$timediff = date("H",strtotime($timein) - strtotime($timeout));
You can also change to format of the result,
check: http://php.net/manual/en/function.date.php
If you first set them to full dates:
$timein = "09:00";
$timeout = "17:00";
$datein = strtotime(date("Y-m-d ".$timein);
$dateout = strtotime(date("Y-m-d ".$timeout);
So, in fact the date you are using (todays date) can be any other date given since it's all about the time between the hours. Then you can create the php date function:
$hourIn = date("G", $datein); // = 9
$hourOut = date("G", $dateout); // = 17
Followed by simple math:
$diff = $hourOut - $hourIn; // = 8
You can use strtotime() for time calculation.
$timein = strtotime('09:00');
$timeout = strtotime('17:00');
$timediff = $timein - $timeout;
echo 'Time: '.date('H:i:s', $timediff);
Break the problem down into two steps.
Convert each time into a number of seconds since midnight.
Calculate the difference between two times.
This breaks the larger problem down into basic problems which can be solved more easily. It is a very valuable tool in the programmer's belt.
For the second part, be sure to handle midnight the way you need to for your data. Perhaps if the timeout is before the timein, then you'll need to add 24 hours to the total? That's just a guess, because I do not know your data.

Date is not formatting time correctly PHP

Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";

Adding hours in PHP

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/

PHP Countdown 48 hours from a set datetime

I'm looking to create a countdown timer in PHP. When a user clicks a button it saves the current date & time into a database entry, then it should take the difference of that entry with the current date and time and 'doSomething' when the difference is larger than 48 hours.
My issue is with the actual countdown.
I've tried the following but to no avail it only counts the difference of the of both strings and doesn't take the days in account. Not only that but it also appears to show the resulted difference incorrectly:
$d1=strtotime("2012-07-08 11:14:15");
$d2=strtotime("2012-07-09 12:14:15");
$diff = round(abs($d1 - $d2));
$cd = date("H:i:s", $diff);
echo $cd;
Thanks for helping me Yan.kun from StackOverflow! The code submitted below was the solution! In order to display strictly the countdown in hours:minutes:seconds I replaced the printf() code with the following:
$hours = ($result->d*24)+$result->h;
$minutes = $result->i;
$seconds = $result->s;
echo $hours . ":" . $minutes . ":" . $seconds;
Try this instead:
$d1 = new DateTime("2012-07-08 11:14:15");
$d2 = new DateTime("2012-07-09 12:14:15");
$result = $d1->diff($d2);
printf('difference is %d day(s), %d hour(s), %d minute(s)', $result->d, $result->h, $result->i);
EDIT:
And if you have no PHP 5.3 available, you can convert your times into an unix epoch timestamp like described in this answer.
not sure if this is what you want:
$d1=strtotime("2012-11-18 11:14:15");//2 days earlier
$d2=strtotime("2012-11-20 11:14:15");//today
$diff = $d2 - $d1; //difference in seconds.
$hours = $diff/60/60;//translation to minutes then to hours
echo $hours;
if($hours>48){
echo "Script";
}

Categories