# Find total time using mysql query when you have two datetime fields.

278 views
``````SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(date_out,date_in)))) as total FROM mytable
``````

Also you can find this using php code which is Find total time using mysql query when you have two datetime fields.

``````function sum_the_time(\$time1, \$time2) {
\$times = array(\$time1, \$time2);
\$seconds = 0;
foreach (\$times as \$time)
{
list(\$hour,\$minute,\$second) = explode(':', \$time);
\$seconds += \$hour*3600;
\$seconds += \$minute*60;
\$seconds += \$second;
}
\$hours = floor(\$seconds/3600);
\$seconds -= \$hours*3600;
\$minutes  = floor(\$seconds/60);
\$seconds -= \$minutes*60;
// return "{\$hours}:{\$minutes}:{\$seconds}";
return sprintf('%02d:%02d:%02d', \$hours, \$minutes, \$seconds);
}

function diff_the_time(\$time1, \$time2) {
\$seconds=strtotime(\$time1)-strtotime(\$time2);
\$hours = floor(\$seconds/3600);
\$seconds -= \$hours*3600;
\$minutes  = floor(\$seconds/60);
\$seconds -= \$minutes*60;
// return "{\$hours}:{\$minutes}:{\$seconds}";
return sprintf('%02d:%02d:%02d', \$hours, \$minutes, \$seconds);
}
``````
posted Aug 23, 2014