# PHP: Calculate Real Differences Between Two Dates or Timestamps - Comment Page: 5

I was using simple function to calculate difference between two dates and timestamps until I noticed, it's not working correctly in long intervals. It's very easy to calculate difference between two timestamps in seconds, but it's much more complicated print difference in human readable format. The Internet can be found in a wide range of ways to do this thing, but as a rule they use a fixed amount of seconds for the year and the month. So if we calculate year with using 365 or 365.25 days and month using 30 or 31 then the difference is not accurate, because of leap years, DST (Daylight Saving Time) and so on. Because of this problem, I decided to make a function (at least in the short...

## 226 comments on “PHP: Calculate Real Differences Between Two Dates or Timestamps - Comment Page: 5”

1 3 4 5 6 7 10
1. // if same day
if (\$time1 == \$time2) { echo “TODAY”; }

// if past
if (\$time1 \$time2) {
\$ttime = \$time1;
\$time1 = \$time2;
\$time2 = \$ttime;
}

2. Hello
I as well like your dateDiff function thank you for sharing this function

I am using your above function on a timesheet db application where I calculate the total of the time worked ( time IN 7:00 AM time Out 5: 00 PM )

your function displays the time diff as expectected when displaying one timesheet or the time of single timesheets.
I display the last two weeks timesheets and I would need the total sum of worked time displayed. I wonder if I can modify your function maybe with a staic value

function dateDiff(\$time1, \$time2, \$precision = 6) {
static \$SumTotalTime;

\$times[] = \$value . ” ” . \$interval;
\$SumTotalTime = (\$SumTotalTime + \$value);
\$count++;

can someone please point me in the right direction how I could display the total time processed with the function from the page

thank you

• Hi Vincent,

Glad to hear that you like dateDiff function.

In your case, is certainly an easier way to calculate the time between the two timestamp. I wrote quick class for you. If I understand correctly, what you’re doing, so the following example might work.

TimestampCalc class

``````
class TimestampCalc {
private \$total_seconds;

public function __construct() {
\$this->total_seconds = 0;
}

public function resetTotal() {
\$this->total_seconds = 0;
}

// Time format is UNIX timestamp or
// PHP strtotime compatible strings
// If not numeric then convert texts to unix timestamps
if (!is_int(\$time1)) {
\$time1 = strtotime(\$time1);
}
if (!is_int(\$time2)) {
\$time2 = strtotime(\$time2);
}

// If time1 is bigger than time2
// Then swap time1 and time2
if (\$time1 > \$time2) {
\$ttime = \$time1;
\$time1 = \$time2;
\$time2 = \$ttime;
}

\$this->total_seconds += (\$time2 - \$time1);
}

public function getPlainTotal() {
return \$this->total_seconds;
}

public function getFormattedTotal() {
\$diffs = array();
\$diffs['hour'] =  floor (\$this->total_seconds / (60 * 60));
// extract minutes
\$minutes = \$this->total_seconds % (60 * 60);
\$diffs['minute'] = floor (\$minutes / 60);
// extract seconds
\$seconds = \$minutes % 60;
\$diffs['second'] = \$seconds % 60;

\$count = 0;
\$times = array();
// Loop thru all diffs
foreach (\$diffs as \$interval => \$value) {
// if value is bigger than 0
if (\$value > 0) {
// Add s if value is not 1
if (\$value != 1) {
\$interval .= "s";
}
// Add value and interval to times array
\$times[] = \$value . " " . \$interval;
\$count++;
}
}
// Return string with times
return implode(", ", \$times);
}
}
``````

Example usage

``````
\$tc = new TimestampCalc();

// Example1 times

// Example1 print
echo "Example1:\n";
echo \$tc->getPlainTotal() . " seconds\n";
echo \$tc->getFormattedTotal() . "\n";

\$tc->resetTotal();

// Example2 times

// Example2 print
echo "\nExample2:\n";
echo \$tc->getPlainTotal() . " seconds\n";
echo \$tc->getFormattedTotal() . "\n";
``````

Output:

```Example1:
75900 seconds
21 hours, 5 minutes

Example2:
87216 seconds
24 hours, 13 minutes, 36 seconds
```
3. Dear Jr

Your class works but i think you maybe miss understood my goal

when displaying one time sheet your function and now your class works as expected ..

MY DB Tbl. TimeIN 08:00AM TimeOut: 05:00PM
I would display under the time sheet that the employee worked 9 hrs

But I as well would like to display the total hours and min worked when multiple timesheets are selected .. .

let me show you some code :

while(\$get_employee_sheet_data = mysql_fetch_array(\$check_employee_timeSheets)) {
\$EmplSheetID = \$get_employee_sheet_data[‘TimeSheetID’];
\$EmplSheetDate =\$get_employee_sheet_data[‘TimeSheetDate’];
\$EmplSheetJobID = \$get_employee_sheet_data[‘TimeSheetJobTitleID’];
\$EmplSheetJobTitle = \$get_employee_sheet_data[‘TimeSheetJobTitle’];
\$EmplSheetIn = \$get_employee_sheet_data[‘TimeSheetTimeIn’];
\$EmplSheetOut = \$get_employee_sheet_data[‘TimeSheetTimeOut’];
\$tc = new TimestampCalc();

echo ““. \$EmplSheetDate .” “. \$EmplSheetJobTitle .” (“. \$tc->getFormattedTotal() .”)

….

the above recordset shows the time worked of one record, just now I would need the total times calculated by your function so I have a total of the selected recordset exsample 10 timesheets etc.

thank you for your input and smarts

• Hi again Vincent,

Actually, I understood what you wanted to do, but only partially. :) Example works for collecting total time and returns it as formatted, but can’t return every added time as formatted. So let’s try again:

New version of TimestampCalc class

``````
class TimestampCalc {
private \$total_seconds;

public function __construct() {
\$this->resetTotal();
}

// Reset total time
public function resetTotal() {
\$this->total_seconds = 0;
}

// Time format is UNIX timestamp or
// PHP strtotime compatible strings
// Returns formatted time
// If not numeric then convert texts to unix timestamps
if (!is_int(\$time1)) {
\$time1 = strtotime(\$time1);
}
if (!is_int(\$time2)) {
\$time2 = strtotime(\$time2);
}

// If time1 is bigger than time2
// Then swap time1 and time2
if (\$time1 > \$time2) {
\$ttime = \$time1;
\$time1 = \$time2;
\$time2 = \$ttime;
}

\$time = (\$time2 - \$time1);

\$this->total_seconds += \$time;

return \$this->formatTime(\$time);
}

// Returns plain total time
public function getPlainTotal() {
return \$this->total_seconds;
}

// Returns formatted total time
public function getFormattedTotal() {
return \$this->formatTime(\$this->total_seconds);
}

private function formatTime(\$total_seconds) {
\$diffs = array();
\$diffs['hour'] =  floor (\$total_seconds / (60 * 60));
// extract minutes
\$minutes = \$total_seconds % (60 * 60);
\$diffs['minute'] = floor (\$minutes / 60);
// extract seconds
\$seconds = \$minutes % 60;
\$diffs['second'] = \$seconds % 60;

\$count = 0;
\$times = array();
// Loop thru all diffs
foreach (\$diffs as \$interval => \$value) {
// if value is bigger than 0
if (\$value > 0) {
// Add s if value is not 1
if (\$value != 1) {
\$interval .= "s";
}
// Add value and interval to times array
\$times[] = \$value . " " . \$interval;
\$count++;
}
}
// Return string with times
return implode(", ", \$times);
}
}
``````

Example usage

``````
\$tc = new TimestampCalc();

// Example1 print
echo "Example1:\n";
// Example1 times
echo \$tc->addTimeDiff("2011-04-08 08:15:00", "2011-04-08 12:45:00") . "\n";
echo \$tc->addTimeDiff("2011-04-09 06:35:00", "2011-04-09 16:25:00") . "\n";
echo \$tc->addTimeDiff("2011-04-10 07:45:00", "2011-04-10 14:30:00") . "\n";

echo "Plain total: " . \$tc->getPlainTotal() . " seconds\n";
echo "Formatted total: " . \$tc->getFormattedTotal() . "\n";

\$tc->resetTotal();

// Example2 print
echo "\nExample2:\n";

// Example2 times
echo \$tc->addTimeDiff("2011-04-08 09:11:47", "2011-04-08 17:42:41") . "\n";
echo \$tc->addTimeDiff("2011-04-09 08:38:17", "2011-04-09 16:31:28") . "\n";
echo \$tc->addTimeDiff("2011-04-10 06:44:01", "2011-04-10 14:33:32") . "\n";

echo "Plain total: " . \$tc->getPlainTotal() . " seconds\n";
echo "Formatted total: " . \$tc->getFormattedTotal() . "\n";
``````

Output

```Example1:
4 hours, 30 minutes
9 hours, 50 minutes
6 hours, 45 minutes
Plain total: 75900 seconds
Formatted total: 21 hours, 5 minutes

Example2:
8 hours, 30 minutes, 54 seconds
7 hours, 53 minutes, 11 seconds
7 hours, 49 minutes, 31 seconds
Plain total: 87216 seconds
Formatted total: 24 hours, 13 minutes, 36 seconds
```

``````
// Create class just once
\$tc = new TimestampCalc();

// ....

while(\$get_employee_sheet_data = mysql_fetch_array(\$check_employee_timeSheets)) {
\$EmplSheetID = \$get_employee_sheet_data['TimeSheetID'];
\$EmplSheetDate =\$get_employee_sheet_data['TimeSheetDate'];
\$EmplSheetJobID = \$get_employee_sheet_data['TimeSheetJobTitleID'];
\$EmplSheetJobTitle = \$get_employee_sheet_data['TimeSheetJobTitle'];
\$EmplSheetIn = \$get_employee_sheet_data['TimeSheetTimeIn'];
\$EmplSheetOut = \$get_employee_sheet_data['TimeSheetTimeOut'];

// addTimeDiff function returns formatted time

// Print formatted time
echo "". \$EmplSheetDate ." ". \$EmplSheetJobTitle ." (". \$formattedTime .")";

}

// ....

// Loop more timeSheets or something

// Print formatted total time from all added times
echo "Total: " . \$tc->getFormattedTotal() . "\n";
``````
4. Jr thank you for your time and the way of writing the above class, It works well here for my timesheet application.
If you dont mind I would like to keep in touch with you.

Thank you again

5. I have to ask you another question what is in regarding the time difference

I am saving the above times as a varchar in the timesheet table ( 07:00 AM )
I had this issue that the date type is not so practicly in my timesheet application

it works very well now to calculate the times of the timesheet tx to your class ..

However Jr bevore entering new timesheet data into the table I have to check if the times are overlapping with already a saved timesheet. I wonder if you would again direct me in the right direction, i know if the times are saved as date time field i would have a query similar to seee below:

how would you write the timesheet overlap check because my fields are strings

}else{
\$strSql=”SELECT * FROM `TimesheetTbl` WHERE `TimeSheetTimeIN` between ‘\$strSheetTimeIN’ AND ‘\$strSheetTimeOut’ OR `TimeSheetTimeOut`
between ‘\$strSheetTimeIN’ AND ‘\$strSheetTimeOut’ AND `TimeSheetDate` = ‘\$strTimeSheetDate’ AND `TimeSheetUserID` = \$EmpldbID”;
\$check_time_sheet = mysql_query(\$strSql);
echo \$strSql;
if(mysql_num_rows(\$check_time_sheet) != 0){
\$final_report.=”found a recorded timesheet with overlapping times!”;
}else{
….

I wonder should I query first the existing times and format them or is it possible to check the overlapp via sql

6. Jr
I been searching online and testing so much with no success to check the times stored as string in the db for overlapping times . I as well asked in other forums and they say its not possible . I still dont think so . there must be a way of converting the string times on the fly in the sql or maybe in an array when I retrieve the existing times from a recordset.

Jr. If you think its not possible i change the db field type to a date field but it would be so much better if I can leave them as varchar and still validate the input

7. Hi again Vincent,

Nice to hear that my class work on your timesheet application. :)

I’ve been a little busy, but here’s my thoughts to the problem.

First, the best way to store the date and time is of course the database fields that are real date and time types.

But I think that your situation is not impossible. You could use MySQL STR_TO_DATE function to convert your varchar type dates and times to real MySQL dates and times.

STR_TO_DATE Example usage (Linux date format converted to MySQL datetime)

``````
mysql> SELECT STR_TO_DATE('Fri Apr 15 10:13:03 2011', '%a %b %d %H:%i:%s %Y') AS datetime;
+---------------------+
| datetime            |
+---------------------+
| 2011-04-15 10:13:03 |
+---------------------+
1 row in set (0.05 sec)

``````

You could use this method for times and dates separated or concatenate date and time to one varchar and convert it to mysql datetime. This is actually inverse DATE_FORMAT function.

8. Dear Jr

I have an issue with your class and I can not find my error. Your class works everywhere very fine in my application. Today was working on the payroll sytem of my timesheet application. I used your class in the same manner as i did on other screens withhn my app. now when I want to display the times it looks like:
(362201 hours, 45 minutes) (362207 hours, 45 minutes) (362213 hours, 30 minutes)
on a different page with the same times it comes out normal:
(3 hours, 15 minutes) (4 hours, 45 minutes) (4 hours, 45 minutes)
Can you explain and point me to a solution?
thank you

• Hi again Vincent,

It is very hard to say and debug because I don’t know your code exactly where you are using my class.

9. WOOOO!!!! I was stuck on this problem for a while. Thanks for the help. :)

10. On one page is working fine and on the other with the same times it runs different?

here is the code of the page where it gives me the wrong format, time_eader.php holds only your class and I include it on a other pages and the times work well!

>>>>> php

<<<php

\$strDate = trim(\$_POST['txtDate']);
\$strDate2 = trim(\$_POST['txtDate2']);

\$strUsr = \$_POST['chkUsrInclude'];
\$strQueryAtt=" WHERE TimeSheetFiled 1 “;
\$strQueryOrder = ” ORDER BY TimeSheetDate DESC ” ;
if ((strlen(\$strDate) > 0) AND (strlen(\$strDate2) ='”. \$strDate .”‘ “;
}
if ((strlen(\$strDate2) >0) AND (strlen(\$strDate) < 1)){
\$strQueryAtt .=" AND TimeSheetDate <= '". \$strDate2 ."' ";
}

if ((\$strDate2 “”) AND (\$strDate “”)){
\$strQueryAtt .=” AND TimeSheetDate BETWEEN ‘”. \$strDate .”‘ AND ‘”. \$strDate2 .”‘”;
}
\$n=count(\$strUsr);
if (\$n> 0) {
for (\$i=0; \$i

Start:
<input name="txtDate" type="text" id="txtDate" size="10" maxlength="12" readonly="True" value="” onclick=”scwShow(scwID(‘txtDate’),event);” style=”cursor:hand” />

End:
<input name="txtDate2" type="text" id="txtDate2" size="10" maxlength="12" readonly="True" value="” onclick=”scwShow(scwID(‘txtDate2’),event);” style=”cursor:hand”/>

<<php \$strQuery = "SELECT DISTINCT TimeSheetUserID, TimeSheetUsrName FROM `TimesheetTbl` ". \$strQueryAtt . " ";
\$check_employees_in_Sheets = mysql_query(\$strQuery) or die(mysql_error());
if(mysql_num_rows(\$check_employees_in_Sheets) == 0){
echo "no records found in range”;
}else{ ?>

<<<php while(\$get_employee_sheet_data = mysql_fetch_array(\$check_employees_in_Sheets)) {
\$EmplName = \$get_employee_sheet_data['TimeSheetUsrName'];
\$EmplID = \$get_employee_sheet_data['TimeSheetUserID'];
echo "”. \$EmplName . “”;
}
?>

<?php
echo "”;
echo ” “;
echo ” “;
\$strQuery = “SELECT * FROM `TimesheetTbl` “. \$strQueryAtt . ” “. \$strQueryOrder .””;
\$rs_empl_filter_Sheets = mysql_query(\$strQuery) or die(mysql_error());
\$i=mysql_num_rows(\$rs_empl_filter_Sheets);
if(\$i == 0){
echo “no timesheet records found in range”;
}else{

echo “”;
echo “Timesheets: “. \$i .””;
echo “”;
echo ” “;
echo ” “;
echo ” Date”;
echo ” Job”;
echo ” Times”;
echo ” File”;
echo ” “;
echo ” “;
\$tc = new TimestampCalc();
while(\$get_employee_sheet_data = mysql_fetch_array(\$rs_empl_filter_Sheets)) {
\$EmplSheetID = \$get_employee_sheet_data[‘TimeSheetID’];
\$EmplSheetDate =\$get_employee_sheet_data[‘TimeSheetDate’];
\$EmplSheetJobID = \$get_employee_sheet_data[‘TimeSheetJobTitleID’];
\$EmplSheetJobTitle = \$get_employee_sheet_data[‘TimeSheetJobTitle’];
\$EmplSheetIn = \$get_employee_sheet_data[‘TimeSheetTimeIn’];
\$EmplSheetOut = \$get_employee_sheet_data[‘TimeSheetTimeOut’];
\$EmplSheetIn2 = \$get_employee_sheet_data[‘TimeSheetTimeIn2’];
\$EmplSheetOut2 = \$get_employee_sheet_data[‘TimeSheetTimeOut2’];
\$EmplSheetIn3 = \$get_employee_sheet_data[‘TimeSheetTimeIn3’];
\$EmplSheetOut3 = \$get_employee_sheet_data[‘TimeSheetTimeOut3’];

echo “”;
echo “”;
echo ” “;
echo ” “. \$EmplSheetDate .”“;
echo ” “. \$EmplSheetJobTitle .””;
echo ” (“. \$n_total_i .”)”;
if (strlen(\$n_total_i_2) >0) {
echo ” (“. \$n_total_i_2 .”) “;
}
if (strlen(\$n_total_i_3) >0) {
echo ” (“. \$n_total_i_3 .”) “;
}
echo “”;
echo ” “;
echo ” “;
echo ” “;
echo ” “;
echo ” “;
echo ” “;
} // timesheets
echo ” “;
echo ” Total Time: “. \$tc->getFormattedTotal() .””;
}
echo “”;
echo “”;
echo “”;
>>>php

PS: each timesheet can hold multiple times.

11. Jr I found the bug …. .. how strange is this … the only diff on the above page is my sql query what uses select * … I just changed the query and added all the fields names into the query

select TimeSheetTimeIn, TimeSheetTimeOut, TimeSheetTimeIn2, TimeSheetTimeOut2, TimeSheetTimeIn3, TimeSheetTimeOut3,
TimeSheetJobTitle, TimeSheetJobTitleID, TimeSheetJobDescription, TimeSheetDate, TimeSheetFiled FROM `TimesheetTbl` ….

and voila your times are formated correctly

• Hi Vincent,

And nice to hear that you get it working!

12. JR, great blog post. Just what I wanted, thanks!

I just have one question about it… is there any way to exclude certain hours from this count? I’m trying to use this script in an environment that counts working hours, and such it should only count 9 out of 24 hours per day (9 AM to 6 PM).
Unfortunately this goes above my head as far as my PHP/function knowledge goes. Any chance you can assist me on this?

• Well, my situation is as follows:
I have four variables, \$date, \$time, \$enddate and \$endtime. These come from a MySQL database and contain stuff like “2011-05-18” and “13:39:00” for \$date and \$time, and “2011-06-12” and “16:05:00” for \$enddate and \$endtime.

What I want to do here is calculate the hours between those dates, but without weekends and non-working hours (6PM to 9 AM, evening). How would this apply to the loop bit?

• This is slightly more problematic than what I thought of first.

So you have to get first day 13:39 to 18:00 and next days 9:00 to 18:00 and last day 9:00 to 16:05 weekends excluded?

• Yes, like that. I should count all the time that has been passed between time A, date B and time X, date Z. Excluding non-working hours (15 hours each day – 6PM to 9AM) and weekends.

• So something like from Friday 4:35PM to Tuesday 11:10AM should result in 13 hours 45 minutes.

• Hi again Thomas,

So you mean 12 hours 45 minutes?

```1 h 25 min (Friday)
9 h (Monday)
2 h 10 min (Tuesday)

12 h 35 minutes (total)
```

But yes here is example code which should work for you. I wrote this class once for Vincent, but reuse it here now… :)

``````
resetTotal();
}

// Reset total time
public function resetTotal() {
\$this->total_seconds = 0;
}

// Time format is UNIX timestamp or
// PHP strtotime compatible strings
// Returns formatted time
// If not numeric then convert texts to unix timestamps
if (!is_int(\$time1)) {
\$time1 = strtotime(\$time1);
}
if (!is_int(\$time2)) {
\$time2 = strtotime(\$time2);
}

// If time1 is bigger than time2
// Then swap time1 and time2
if (\$time1 > \$time2) {
\$ttime = \$time1;
\$time1 = \$time2;
\$time2 = \$ttime;
}

\$time = (\$time2 - \$time1);

\$this->total_seconds += \$time;

return \$time;
}

// Returns plain total time
public function getPlainTotal() {
return \$this->total_seconds;
}

// Returns formatted total time
public function getFormattedTotal() {
return \$this->formatTime(\$this->total_seconds);
}

private function formatTime(\$total_seconds) {
\$diffs = array();
\$diffs['hour'] =  floor (\$total_seconds / (60 * 60));
// extract minutes
\$minutes = \$total_seconds % (60 * 60);
\$diffs['minute'] = floor (\$minutes / 60);
// extract seconds
\$seconds = \$minutes % 60;
\$diffs['second'] = \$seconds % 60;

\$count = 0;
\$times = array();
// Loop thru all diffs
foreach (\$diffs as \$interval => \$value) {
// if value is bigger than 0
if (\$value > 0) {
// Add s if value is not 1
if (\$value != 1) {
\$interval .= "s";
}
// Add value and interval to times array
\$times[] = \$value . " " . \$interval;
\$count++;
}
}
// Return string with times
return implode(", ", \$times);
}
}

// Set timezone
date_default_timezone_set('UTC');

\$ts_calc = new TimestampCalc();

// Initial info
\$working_day_start_time = '09:00:00';
\$working_day_end_time = '18:00:00';
\$exclude_days = array('Sat', 'Sun');
\$debug = true;
\$line_break = "\n";

// Start date
//\$date = '2011-05-18';
\$date = '2011-06-17';
// Start time
//\$time = '13:39:00';
\$time = '4:35 PM';

// End date
//\$end_date = '2011-06-12';
\$end_date = '2011-06-21';
// End time
//\$end_time = '16:05:00';
\$end_time = '11:10 AM';

// Special handling for start date and time
if (!in_array(date('D', strtotime(\$date)), \$exclude_days)) {
\$t = \$ts_calc->addTimeDiff(\$date . " " . \$time, \$date . " " . \$working_day_end_time);
if (\$debug) {
echo \$date, " is ", date('D', strtotime(\$date)), ', working time ', \$t, " seconds", \$line_break;
}
}

\$date = date("Y-m-d", strtotime("+1 day", strtotime(\$date)));
while (strtotime(\$date) < strtotime(\$end_date)) {
if (!in_array(date('D', strtotime(\$date)), \$exclude_days)) {
\$t = \$ts_calc->addTimeDiff(\$date . " " . \$working_day_start_time, \$date . " " . \$working_day_end_time);
if (\$debug) {
echo \$date, " is ", date('D', strtotime(\$date)), ', working time ', \$t, " seconds", \$line_break;
}
}
\$date = date("Y-m-d", strtotime("+1 day", strtotime(\$date)));
}

// Special handling for start date and time
if (!in_array(date('D', strtotime(\$end_date)), \$exclude_days)) {
\$t = \$ts_calc->addTimeDiff(\$end_date . " " . \$working_day_start_time, \$date . " " . \$end_time);
if (\$debug) {
echo \$date, " is ", date('D', strtotime(\$date)), ', working time ', \$t, " seconds", \$line_break;
}
}

echo \$line_break, "Total time ", \$ts_calc->getFormattedTotal(), \$line_break;

?>
``````

Output, when debug is true

```2011-06-17 is Fri, working time 5100 seconds
2011-06-20 is Mon, working time 32400 seconds
2011-06-21 is Tue, working time 7800 seconds

Total time 12 hours, 35 minutes
```

Earlier example case output “2011-05-18 13:39:00â€³ to “2011-06-12 16:05:00” (note this end date is Sunday)

```2011-05-18 is Wed, working time 15660 seconds
2011-05-19 is Thu, working time 32400 seconds
2011-05-20 is Fri, working time 32400 seconds
2011-05-23 is Mon, working time 32400 seconds
2011-05-24 is Tue, working time 32400 seconds
2011-05-25 is Wed, working time 32400 seconds
2011-05-26 is Thu, working time 32400 seconds
2011-05-27 is Fri, working time 32400 seconds
2011-05-30 is Mon, working time 32400 seconds
2011-05-31 is Tue, working time 32400 seconds
2011-06-01 is Wed, working time 32400 seconds
2011-06-02 is Thu, working time 32400 seconds
2011-06-03 is Fri, working time 32400 seconds
2011-06-06 is Mon, working time 32400 seconds
2011-06-07 is Tue, working time 32400 seconds
2011-06-08 is Wed, working time 32400 seconds
2011-06-09 is Thu, working time 32400 seconds
2011-06-10 is Fri, working time 32400 seconds

Total time 157 hours, 21 minutes
```

I tested this code on Linux command line, so I use “\n” as a line break. If you test this on browser then change line break to

`\$line_break = "";`

This code is not the most “polished” alternative, but should work at least on the basis of quick testing. :) Of course you could copy idea and make this code to fit your own code ;)

Please let me know, if you have some problems, with this?

13. Sorry for the late response.
With some small modifications it worked great, thanks very much!

But how would I be able to put the result in a hh:mm:ss format? That would make it perfect ;)

• Hi Thomas,

Nice to hear that it worked for you. :)

Try to replace timeFormat function with following:

``````
private function formatTime(\$total_seconds) {
\$times = array();
\$times['hour'] =  str_pad(floor(\$total_seconds / (60 * 60)), 2, "0");
// extract minutes
\$minutes = \$total_seconds % (60 * 60);
\$times['minute'] = str_pad(floor(\$minutes / 60), 2, "0");
// extract seconds
\$seconds = \$minutes % 60;
\$times['second'] = str_pad(\$seconds % 60, 2, "0");

// Return string with times
return implode(":", \$times);
}
``````

It should work! ;)

14. Hi,

I read all the comments + check all the codes but its too complicated for me as I am new.

I want the time diff between time now + \$datetime (stored value in sql)

i have 2 variables
1. \$datetime — stored timestamps in sql
2. time(); — current date and time stamps

output will be: 20 sec. ago or 1 hrs. ago and after 24 hrs. 1 day ago

how so i get these value? IF you need full code, i can send you or will post here.

• Hi,

This original function should work for your case normally just use it like:

``````
echo dateDiff(time(), \$datetime_from_mysql, 1);
``````

Let me know, if you have some problems with this.

15. Jr,
I would like to first thank you for all of the help that you have been providing to others here. It is not often that one human will go out of his or her way in the ways that you have.

I have a small issue and I am sure that it is related to way to many hours behind the keyboard. The issue is that I am constantly being returned the same incorrect date no matter what the “previous” date is.

For Example:
``` echo time() . " - " . \$row[logonDateTime] . ""; echo "difference is " . (time() - \$row['logonDateTime']) . ""; echo time() . " - " . \$row[logonDateTime] . ""; echo "difference is " . (time() - \$row['logoffDateTime']) . ""; ```

OUTPUT:
``` 1313117467 - 1313053080 difference is 64387 1313117467 - 1313053080 difference is 62827 ```

How ever when I run it through your OP function like:

``` \$lastLogon = dateDiff(time(), \$row[logonDateTime]); echo \$lastLogon . ""; \$lastLogoff = dateDiff(time(), \$row[logoffDateTime]); echo \$lastLogoff . ""; ```

The result is always (regardless of a change in logonDateTime or logoffDateTime)
``` 41 years, 7 months, 11 days, 2 hours, 53 minutes, 51 seconds 41 years, 7 months, 11 days, 2 hours, 53 minutes, 51 seconds ```

As you can see above when i subtract each of those time stamps from the current time(), A true representation of how many seconds is represented. I am unable to figure out why running it though your function would result in such a consistant inconsistency.

Any suggestions? Before I leave I would like, ore more time, to thank you and applaud you for the time and effort you have put into this one conversation alone. I have been programming in several languages for a while now with php kind of being a bit of a bastard child that i like to take to the park once in a while. In the many years that I have dabbled in programming, I have found less than 3 that were so willing to help the community. I would like to applaud you for your efforts and hope that our fellow humans may see people like you and be more willing to help a neighbor as you have.