Graham wrote:
I have a variable which can be in the format "mm:ss" or "hh:mm:ss". I would
like to extract the total number of seconds from this.
Ie "01:30" would be 90 seconds.
Thanks in advance !
<script type="text/javascript">
var seconds = 0, index = 0;
var t = "01:01:30";
var timeParts = t.split(/:/);
if (timeParts.leng th > 2) { // seconds in hours
seconds += 60 * 60 * parseInt(timePa rts[index], 10);
index++;
}
if (timeParts.leng th > 1) { // seconds in minutes
seconds += 60 * parseInt(timePa rts[index], 10);
index++;
}
seconds += parseInt(timePa rts[index], 10); // seconds
alert(seconds);
</script>
This assumes your variable is either "hh:mm:ss" or "mm:ss" (it even supports
"ss"). If it's ever "dd:hh:mm:s s" or some other format, it will provide
incorrect results.
If you don't need support for "ss", you can remove the condition identified by
"// seconds in minutes".
--
| Grant Wagner <gw*****@agrico reunited.com>
* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html
* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp
* Netscape 6/7 DOM Reference available at:
*
http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 6/7 and Mozilla
*
http://www.mozilla.org/docs/web-deve...upgrade_2.html