By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,954 Members | 1,248 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,954 IT Pros & Developers. It's quick & easy.

Total # in seconds for a given time

P: n/a
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 !

Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Graham wrote on 10 jul 2003 in comp.lang.javascript:
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.


<script>
function hms2sec(v){
a=v.split(":")
if (a.length==2)
r=60*a[0]+1*a[1]
else
r=60*60*a[0]+60*a[1]+1*a[2]
return r
}

alert(hms2sec("01:30"))
alert(hms2sec("12:01:30"))
</script>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 20 '05 #2

P: n/a
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.length > 2) { // seconds in hours
seconds += 60 * 60 * parseInt(timeParts[index], 10);
index++;
}
if (timeParts.length > 1) { // seconds in minutes
seconds += 60 * parseInt(timeParts[index], 10);
index++;
}
seconds += parseInt(timeParts[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:ss" 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*****@agricoreunited.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
Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.