SitePoint Sponsor

Thread: Time difference

1. I was recently asked how to work out the time difference between two timestamps so I thought i'd post the answer here.

Code:
```function time_dif(\$ts1=0,\$ts2=0){

if (\$ts1 < \$ts2){\$temp = \$ts1;\$ts1 = \$ts2;\$ts2 = \$temp;}

\$difference = \$ts1 - \$ts2;

\$seconds = \$difference % 60;
\$total_minutes = (int)(\$difference / 60);
\$minutes = \$total_minutes % 60;
\$total_hours = (int)(\$total_minutes / 60);

if (\$seconds < 10){\$seconds = "0".\$seconds;}
if (\$minutes < 10){\$minutes = "0".\$minutes;}
if (\$total_hours < 10){\$total_hours = "0".\$total_hours;}

return "\$total_hours:\$minutes:\$seconds";
}```
you can test it out @ http://www.guntrisoft.com/dev/james/...val2=982985627

2. An equally effective approach with less processing time. Just though I would share since I too, was asked about this today.

PHP Code:
``` function how_long_time(\$to, \$from) {     return sprintf('<b>Start Time:</b> %s<br><b>End Time:</b> %s<br><b>Elapsed:</b> %02d:%02d:%02d',                     date("m/d/y g:i:s a", \$to),                     date("m/d/y g:i:s a", \$from),                     number_format(floor((\$to - \$from) / 3600), 0),                     number_format(floor((\$to - \$from) / 60), 0),                     number_format((\$to - \$from)%60, 0)                     );     }  ```

3. Slight bug there freddy, when given the values

45667 and 14400

you code returns 08:521:07

see http://www.guntrisoft.com/dev/james/...667&val2=14400

4. although yours is a shed load cleaner than mine at doing it.

5. Ah I see nice call, I better fix that up right away

6. Sorted
Code:
```function how_long_time(\$to, \$from) {
return sprintf('<b>Start Time:</b> %s<br><b>End Time:</b> %s<br><b>Elapsed:</b> %02d:%02d:%02d',
date("m/d/y g:i:s a", \$to),
date("m/d/y g:i:s a", \$from),
number_format(floor((\$to - \$from) / 3600), 0),
number_format(floor((\$to - \$from) / 60)%60, 0),
number_format((\$to - \$from)%60, 0)
);
}```

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•