Adding times

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Tubby
Forum Commoner
Posts: 28
Joined: Thu Oct 17, 2002 5:55 pm

Adding times

Post by Tubby »

Hello,
I'm currently writing a script which logs all the tracks I play on winamp into a mysql database, I've got all that working fine, but want to display some stats on a page, and the one I'm stuck on is total playing time.

In the database on each row with the track title, artist, album is the track length in the fashion mins:seconds in a column called length.

For the stats page how can I add together all the track times from the length column to give a total playing time in hours:mins:seconds, or even better, days:hours:mins:seconds?

Thanks.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Not sure of your exact db setup etc..etc..but here's an example you could modify for your needs.

Code: Select all

<?php

$foo[] = '6:23';
$foo[] = '10:20';
$foo[] = '3:57';

$totalmins = 0;
$totalsecs = 0;
foreach($foo as $bar){
  list($mins, $secs) = explode(':', $bar);
  $totalmins += $mins;
  $totalsecs += $secs;
}

$total = $totalmins * 60 + $totalsecs;
$db = mysql_connect('host', 'user', 'pass');
$sql = "SELECT SEC_TO_TIME($total) AS totaltime";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
echo $row['totaltime'];

?>
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I think the easiest way would be to extract all the song lengths, break them down into seconds, then build the time back up into minutes, hours, and days. markl999's solution seems pretty short though
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Tubby
Forum Commoner
Posts: 28
Joined: Thu Oct 17, 2002 5:55 pm

Post by Tubby »

markl999 wrote:Not sure of your exact db setup etc..etc..but here's an example you could modify for your needs.

Code: Select all

<?php

$foo[] = '6:23';
$foo[] = '10:20';
$foo[] = '3:57';

$totalmins = 0;
$totalsecs = 0;
foreach($foo as $bar){
  list($mins, $secs) = explode(':', $bar);
  $totalmins += $mins;
  $totalsecs += $secs;
}

$total = $totalmins * 60 + $totalsecs;
$db = mysql_connect('host', 'user', 'pass');
$sql = "SELECT SEC_TO_TIME($total) AS totaltime";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
echo $row['totaltime'];

?>
Thanks, that works nicely :D
Post Reply