Hello all. Can anyone show me the best way to convert a duration consisting of only minutes and seconds (such as 2:15) into all seconds (which would be 135 based on my original 2:15). Thanks in advance!

Recommended Answers

All 5 Replies

function toSeconds(str){
  str=str.split(':');
  switch( str.length )
  {
    case 2: return str[0]*60 + str[1]*1;
    case 3: return str[0]*3600 + str[1]*60 + str[2]*1;
  }
}

alert( toSeconds("2:15") )

You could explode the string using the ":" as the delimiter. This will give you an array with two entries. Take the first entry, multiply it by 60 then add the result to the second entry and you're done.

Yes As chrishea said its look like

<?php
	$duration="2:15";
	$duration_arr=explode(":",$duration);
	$seconds=$duration_arr[0]*60+$duration_arr[1];
	echo $seconds;
?>
function toSeconds($str){
  $str=explode(':',$str);
  switch( count($str) )
  {
    case 2: return $str[0]*60 + $str[1];
    case 3: return $str[0]*3600 + $str[1]*60 + $str[2];
  }
return 0;
}

echo( toSeconds("2:15") );//mm:ss
echo( toSeconds("1:00:15") );//hh:mm:ss

thanks everyone ive got it working great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.