Total # in seconds for a given time

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Graham

    #1

    Total # in seconds for a given time

    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 !



  • Evertjan.

    #2
    Re: Total # in seconds for a given time

    Graham wrote on 10 jul 2003 in comp.lang.javas cript:
    [color=blue]
    > 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.
    >[/color]

    <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)

    Comment

    • Grant Wagner

      #3
      Re: Total # in seconds for a given time

      Graham wrote:
      [color=blue]
      > 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 ![/color]

      <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 <gwagner@agrico reunited.com>

      * Client-side Javascript and Netscape 4 DOM Reference available at:
      *


      * 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


      Comment

      Working...