# Time difference

• Feb 24, 2001, 00:13
Drinky
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
• Feb 24, 2001, 00:37
freddydoesphp

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)                     );     }  ```
• Feb 24, 2001, 00:46
Drinky
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
• Feb 24, 2001, 00:48
Drinky
although yours is a shed load cleaner than mine at doing it.
• Feb 24, 2001, 00:48
freddydoesphp
Ah I see nice call, I better fix that up right away :D
• Feb 24, 2001, 01:04
Drinky
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)                     );     }```