Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q238 How can I convert a form field value in HH:MM:SS to pure seconds?

You are here: irt.org | FAQ | JavaScript | Date | Q238 [ previous next ]

The following will work on all versions of JavaScript:

<SCRIPT LANGUAGE="JavaScript"><!--
function splits(string,text) {
// splits string at text
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return;
    if (i == -1) {
        splitArray[splitIndex++] = string;
        return;
    }

    splitArray[splitIndex++] = string.substring(0,i);

    if (i+txtLength < strLength)
        splits(string.substring(i+txtLength,strLength),text);

    return;
}

function split(string,text) {
    splitIndex = 0;
    splits(string,text);
}
//--></SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.1"><!--
function split(string,text) {
    splitArray = string.split(text);
    splitIndex = splitArray.length;
}
//--></SCRIPT>

<SCRIPT LANGUAGE="JavaScript"><!--
var splitIndex = 0;
var splitArray = new Array();

function calculateTime() {
    splitIndex = 0;
    split(document.myForm.myTime.value,':');

    for (var i=splitIndex-1, j=1, answer=0; i>=0; i=i-1, j=j*60)
        answer += splitArray[i]*j - 0;

    document.myForm.mySeconds.value = answer;
}
//--></SCRIPT>

<FORM NAME="myForm">
<P>HH:MM:SS = <INPUT NAME="myTime" TYPE="TEXT" MAXLENGTH="8" LENGTH="10">
<P>Seconds = <INPUT NAME="mySeconds" TYPE="TEXT">
<P><INPUT TYPE="BUTTON" VALUE="Calculate" onClick="calculateTime()">
</FORM>

©2018 Martin Webb