adding 2 times together

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

    #1

    adding 2 times together

    Hey Gang, I'm trying to figure out the best way to add two times together of
    the format hh:mm:ss any suggestions would be great thanks Todd


  • Ivo

    #2
    Re: adding 2 times together

    "Stormkid" <bakert2@golden gate.net> wrote in message
    news:41586752$0 $286$8f4e7992@n ewsreader.golde ngate.net...[color=blue]
    > Hey Gang, I'm trying to figure out the best way to add two times together[/color]
    of[color=blue]
    > the format hh:mm:ss any suggestions would be great thanks Todd
    >[/color]

    Convert all to seconds, add, then convert back. This way you can easily add
    a third time later. For example:

    var t1='12:34:56';
    var t2='10:10:03';

    t1=t1.split(/\D/);
    t2=t2.split(/\D/);
    var x1=parseInt(t1[0])*60*60 + parseInt(t1[1])*60 + parseInt(t1[2]);
    var x2=parseInt(t2[0])*60*60 + parseInt(t2[1])*60 + parseInt(t2[2]);
    var s=x1+x2;
    var m=Math.floor(s/60); s=s%60;
    var h=Math.floor(m/60); m=m%60;
    var d=Math.floor(h/24); h=h%24;
    alert(d+':'+h+' :'+m+':'+s);

    You may wish to add leading zero's to numbers below 10 etc.
    --Iv


    Comment

    • Fred Oz

      #3
      Re: adding 2 times together

      Ivo wrote:
      [snip][color=blue]
      >
      > Convert all to seconds, add, then convert back. This way you can easily add
      > a third time later. For example:[/color]
      [snip]

      Here is a modification of Ivo's example, I've created toSec(), toHr()
      and toDay() functions. Of course there is no input validation and the
      actual functions can probably be made more efficient.

      You may still want to add leading zeros and include either toHr() or
      toDay(), not both.

      It is also more correct to use

      this.form.eleme nts['time1'].value

      rather than the shorter but probably just as reliable:

      this.form.time1 .value


      Cheers, Fred.

      <script type="text/javascript">
      function toSec(t) {
      var b = t.split(/\D/);
      return (+b[0])*60*60 + (+b[1])*60 + (+b[2]);
      }

      function toHr(s){
      var m = Math.floor(s/60);
      var h = Math.floor(m/60);
      return h + ':' + m%60 + ':' + s%60;
      }

      function toDay(s){
      var m = Math.floor(s/60);
      var h = Math.floor(m/60);
      var d = Math.floor(h/24);
      return d + ':' + h%24 + ':' + m%60 + ':' + s%60;
      }
      </script>

      <p>Enter times of format: hh:mm:ss</p>
      <form name="fred" action="">
      <input type="text" name="time1" cols="10">&nbsp ;&nbsp;
      <input type="text" name="time2" cols="10"><br>
      <input type="button" value="Add times" onclick="
      alert('Hours: ' + toHr(toSec(this .form.time1.val ue)
      + toSec(this.form .time2.value))
      + '\nDays: ' + toDay(toSec(thi s.form.time1.va lue)
      + toSec(this.form .time2.value))) ;
      ">
      </form>

      Comment

      • RobG

        #4
        Re: adding 2 times together

        Fred Oz wrote:

        [snip][color=blue]
        > You may still want to add leading zeros ...[/color]
        [snip]


        Here's an "add leading zeros" function that will add a
        leading zero if the number passed has only one digit:

        function addZero(x) {
        if (String(x).leng th < 2) x = '0' + x;
        return x;
        }


        Use it like this in toHr()

        return addZero(h) + ':' + addZero(m%60) + ':'
        + addZero(s%60);


        Rob

        Comment

        • Hal Rosser

          #5
          Re: adding 2 times together

          The result would be undefined
          Why would you want to add - say 11:55pm to 7:36am ?
          I could see adding 2 hours and 45 minutes to a time, or something like that.
          Please clue us in on your purpose

          "Stormkid" <bakert2@golden gate.net> wrote in message
          news:41586752$0 $286$8f4e7992@n ewsreader.golde ngate.net...[color=blue]
          > Hey Gang, I'm trying to figure out the best way to add two times together[/color]
          of[color=blue]
          > the format hh:mm:ss any suggestions would be great thanks Todd
          >
          >[/color]


          ---
          Outgoing mail is certified Virus Free.
          Checked by AVG anti-virus system (http://www.grisoft.com).
          Version: 6.0.770 / Virus Database: 517 - Release Date: 9/27/2004


          Comment

          • Dr John Stockton

            #6
            Re: adding 2 times together

            JRS: In article <41586752$0$286 $8f4e7992@newsr eader.goldengat e.net>,
            dated Mon, 27 Sep 2004 14:17:40, seen in news:comp.lang. javascript,
            Stormkid <bakert2@golden gate.net> posted :[color=blue]
            >Hey Gang, I'm trying to figure out the best way to add two times together of
            >the format hh:mm:ss any suggestions would be great thanks Todd[/color]

            It makes no sense to add times, but it is perfectly OK to add durations.

            The following illustrates what may be the shortest codes, for totals
            less than 24 hours :-

            D0 = "1970/1/3 " ; G = " GMT"
            T1 = "11:22:33"
            T2 = "01:55:44"

            T3 = (new Date(+new Date(D0+T1+G) + +new Date(D0+T2+G))) .toGMTString(). m
            atch(/\d\d:\d\d:\d\d/)

            T3 = (new Date(+new Date(D0+T1+G) + +new Date(D0+T2+G))) .toGMTString(). s
            ubstr(16, 8)

            The second makes more assumptions. Both are slightly tested.


            The method of Iv (Ivo) fails if any field is 08 or 09 (FAQ 4.12). Using
            parseInt() serves no purpose for hh & mm, and a unary + is enough for
            ss.

            Fred's looks OK apart from leading zeroes; I think that it has two
            superfluous (+ ) .

            Rob's usable leading zero function has the defects that it sometimes
            returns a string & sometimes a number, and that if it returns a number
            the number-to-string conversion will be repeated. Consider
            if ((x=String(x)). length < 2) x = '0' + x;

            <FAQENTRY> Optimal LZ function needed!

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
            <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
            <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
            <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

            Comment

            • rh

              #7
              Re: adding 2 times together

              Dr John Stockton wrote:
              <...>[color=blue]
              > and that if it returns a number
              > the number-to-string conversion will be repeated. Consider
              > if ((x=String(x)). length < 2) x = '0' + x;
              >
              > <FAQENTRY> Optimal LZ function needed![/color]

              Optimal is always desirable, but it seems that there is often no
              single optimally efficient computation, and/or optimally expressed
              computation, because of the variations in the ways in which JS engines
              peform in different browsers. Whether, for example, a type conversion
              is carried out more than once may be less important regarding
              computational efficiency than the actual expression used to manifest
              the result.

              In this given case, differences in performance will likely occur based
              on whether the input value is provided as a string or as an integer.
              A couple of alternatives to your suggestion above, always returning a
              string, are:

              x = "" + (-(x > 9) && "") + +x;

              and

              x = x < 10 ? "0" + +x : "" +x;

              with the former being somewhat oblique, but reasonably efficient (and
              just slightly different in the treatment of extraneous leading zeros
              in the input string), while the latter is expressed more clearly, and
              is more efficient with string input. The latter, without saying it is
              the best that can be done, should also provide better balance of
              efficient computation across browsers and input type.

              ../rh

              Comment

              • Dr John Stockton

                #8
                Re: adding 2 times together

                JRS: In article <290e65a0.04092 81824.78521eeb@ posting.google. com>,
                dated Tue, 28 Sep 2004 19:24:33, seen in news:comp.lang. javascript, rh
                <codeHanger@yah oo.ca> posted :[color=blue]
                >Dr John Stockton wrote:
                ><...>[color=green]
                >> and that if it returns a number
                >> the number-to-string conversion will be repeated. Consider
                >> if ((x=String(x)). length < 2) x = '0' + x;
                >>
                >> <FAQENTRY> Optimal LZ function needed![/color]
                >
                >Optimal is always desirable, but it seems that there is often no
                >single optimally efficient computation, and/or optimally expressed
                >computation, because of the variations in the ways in which JS engines
                >peform in different browsers. Whether, for example, a type conversion
                >is carried out more than once may be less important regarding
                >computationa l efficiency than the actual expression used to manifest
                >the result.
                >
                >In this given case, differences in performance will likely occur based
                >on whether the input value is provided as a string or as an integer.[/color]

                In the overwhelming majority of cases, the programmer will know whether
                the input is a string or an integer.

                The Leading Zero function is essentially a function for integer input.
                If such string padding is wanted, it can either be done using a general
                string padder, or an optimised string padder, or by tolerably
                inefficient use of an integer function.

                Rob's, omitting String( ) , is presumably optimum for strings.

                One important question is whether it is *certain* that the number input
                will be an integer in 0..99. If it is *certain* - which is the case for
                getHours, etc. - then more methods become available, such as adding 100,
                converting to string, and taking the last two characters (which is the
                fastest way I know in MSIE4 VBscript). Otherwise, I would choose to
                preserve the numerical value at the expense of format.
                [color=blue]
                >A couple of alternatives to your suggestion above, always returning a
                >string, are:
                >
                > x = "" + (-(x > 9) && "") + +x;
                >
                >and
                >
                > x = x < 10 ? "0" + +x : "" +x;
                >
                >with the former being somewhat oblique, but reasonably efficient (and
                >just slightly different in the treatment of extraneous leading zeros
                >in the input string), while the latter is expressed more clearly, and
                >is more efficient with string input. The latter, without saying it is
                >the best that can be done, should also provide better balance of
                >efficient computation across browsers and input type.[/color]

                The second + seems unnecessary in the latter.

                For non-negative integers,
                '0'.substring(X >=10)+X // short but slow?
                '0'.substr(X>=1 0)+X // shorter but slow?
                I use
                function LZ(x) { return (x<0||x>=10?"": "0") + x }


                --
                © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                Comment

                • rh

                  #9
                  Re: adding 2 times together

                  Dr John Stockton wrote:
                  [color=blue]
                  > <codeHanger@yah oo.ca> posted :[color=green]
                  > >Dr John Stockton wrote:
                  > ><...>[color=darkred]
                  > >> and that if it returns a number
                  > >> the number-to-string conversion will be repeated. Consider
                  > >> if ((x=String(x)). length < 2) x = '0' + x;
                  > >>
                  > >> <FAQENTRY> Optimal LZ function needed![/color]
                  > >
                  > >Optimal is always desirable, but it seems that there is often no
                  > >single optimally efficient computation, and/or optimally expressed
                  > >computation, because of the variations in the ways in which JS engines
                  > >peform in different browsers. Whether, for example, a type conversion
                  > >is carried out more than once may be less important regarding
                  > >computationa l efficiency than the actual expression used to manifest
                  > >the result.
                  > >
                  > >In this given case, differences in performance will likely occur based
                  > >on whether the input value is provided as a string or as an integer.[/color]
                  >
                  > In the overwhelming majority of cases, the programmer will know whether
                  > the input is a string or an integer.
                  >[/color]

                  Possibly. But perhaps in a typeless language, in the overwhelming
                  majority of cases, it shouldn't be necessary for the programmer to
                  differentiate between the two. If it is, then it seems most sensible
                  to present the utility a prototype of the core object (not that you've
                  suggested anything to the contrary).
                  [color=blue]
                  > The Leading Zero function is essentially a function for integer input.
                  > If such string padding is wanted, it can either be done using a general
                  > string padder, or an optimised string padder, or by tolerably
                  > inefficient use of an integer function.
                  >
                  > Rob's, omitting String( ) , is presumably optimum for strings.[/color]

                  Somewhat surprisingly, it appears not to be. And that's what I meant
                  when saying "optimal" is hard to achieve as it depends on which JS
                  engine is performing the computation. Outside IE, computation
                  efficiency of that expression in several of the more popular browsers
                  (even with String() omitted) ranges in my tests from slow to dismal.

                  The point is that it is non-trivial to assess computational efficiency
                  by simply looking at the operations in an expression.
                  [color=blue]
                  >
                  > One important question is whether it is *certain* that the number input
                  > will be an integer in 0..99. If it is *certain* - which is the case for
                  > getHours, etc. - then more methods become available, such as adding 100,
                  > converting to string, and taking the last two characters (which is the
                  > fastest way I know in MSIE4 VBscript). Otherwise, I would choose to
                  > preserve the numerical value at the expense of format.
                  >[color=green]
                  > >A couple of alternatives to your suggestion above, always returning a
                  > >string, are:
                  > >
                  > > x = "" + (-(x > 9) && "") + +x;
                  > >
                  > >and
                  > >
                  > > x = x < 10 ? "0" + +x : "" +x;
                  > >[/color][/color]
                  <...>[color=blue]
                  >
                  > The second + seems unnecessary in the latter.[/color]

                  It's there to allow for a string with extraneous leading zeros, e.g.,
                  input of "09", which would be returned as "009" otherwise.
                  [color=blue]
                  >
                  > For non-negative integers,
                  > '0'.substring(X >=10)+X // short but slow?
                  > '0'.substr(X>=1 0)+X // shorter but slow?[/color]

                  Also, perhaps:

                  ["0",""][+(x>=10)]+x; // short but (surprisingly) slow
                  [color=blue]
                  > I use
                  > function LZ(x) { return (x<0||x>=10?"": "0") + x }[/color]

                  Which is good, probably optimal -- to be improved only by making it a
                  prototype :).

                  ../rh

                  Comment

                  • Grant Wagner

                    #10
                    Re: adding 2 times together

                    rh wrote:
                    [color=blue][color=green][color=darkred]
                    > > > x = x < 10 ? "0" + +x : "" +x;
                    > > >[/color][/color]
                    > <...>[color=green]
                    > >
                    > > The second + seems unnecessary in the latter.[/color]
                    >
                    > It's there to allow for a string with extraneous leading zeros, e.g.,
                    > input of "09", which would be returned as "009" otherwise.
                    >[color=green]
                    > > I use
                    > > function LZ(x) { return (x<0||x>=10?"": "0") + x }[/color]
                    >
                    > Which is good, probably optimal -- to be improved only by making it a
                    > prototype :).[/color]

                    But allows for a string with extraneous leading zeros:

                    function LZ(x) { return (x<0||x>=10?"": "0") + x }
                    alert(LZ('09')) ;

                    This could be corrected with:

                    function LZ(x) { return (x<0||x>=10?"": "0") + +x }
                    alert(LZ('09')) ;

                    Alternatively:

                    String.prototyp e.LZ = function() { return (+this).LZ(); }
                    Number.prototyp e.LZ = function() { return (this < 0 || this >= 10 ? "" : "0")
                    + this; }
                    alert("09".LZ() ); alert((9).LZ()) ;

                    --
                    Grant Wagner <gwagner@agrico reunited.com>
                    comp.lang.javas cript FAQ - http://jibbering.com/faq

                    Comment

                    • Dr John Stockton

                      #11
                      Re: adding 2 times together

                      JRS: In article <290e65a0.04092 91834.3ca8bf2b@ posting.google. com>,
                      dated Wed, 29 Sep 2004 19:34:50, seen in news:comp.lang. javascript, rh
                      <codeHanger@yah oo.ca> posted :
                      [color=blue]
                      > But perhaps in a typeless language, in the overwhelming
                      >majority of cases, it shouldn't be necessary for the programmer to
                      >differentiat e between the two.[/color]

                      It is trivial, efficient, and not necessary.
                      [color=blue]
                      > If it is, then it seems most sensible
                      >to present the utility a prototype of the core object (not that you've
                      >suggested anything to the contrary).[/color]

                      To suit all cases, ISTM that it would need to be added to String and
                      Number. It's briefer to use LZ(D.getDate()) than D.getDate().LZ( ), too!

                      [color=blue][color=green]
                      >> The Leading Zero function is essentially a function for integer input.
                      >> If such string padding is wanted, it can either be done using a general
                      >> string padder, or an optimised string padder, or by tolerably
                      >> inefficient use of an integer function.
                      >>
                      >> Rob's, omitting String( ) , is presumably optimum for strings.[/color]
                      >
                      >Somewhat surprisingly, it appears not to be.[/color]

                      It would become
                      function addZero(x) { if (x.length < 2) x = '0' + x ; return x }

                      function addZero(x) { return x.length < 2 ? '0' + x : x }

                      is perhaps better, though.
                      [color=blue]
                      > And that's what I meant
                      >when saying "optimal" is hard to achieve as it depends on which JS
                      >engine is performing the computation. Outside IE, computation
                      >efficiency of that expression in several of the more popular browsers
                      >(even with String() omitted) ranges in my tests from slow to dismal.[/color]

                      In comparison with ???
                      [color=blue]
                      >The point is that it is non-trivial to assess computational efficiency
                      >by simply looking at the operations in an expression.[/color]

                      Indeed. The easiest way is to post it here, claim it as good, and wait
                      for results.

                      --
                      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                      <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                      <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                      <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                      Comment

                      • Dr John Stockton

                        #12
                        Re: adding 2 times together

                        JRS: In article <415C2E6D.C6CD9 6DC@agricoreuni ted.com>, dated Thu, 30
                        Sep 2004 16:01:28, seen in news:comp.lang. javascript, Grant Wagner
                        <gwagner@agrico reunited.com> posted :[color=blue]
                        >rh wrote:[/color]
                        JRS wrote :[color=blue][color=green][color=darkred]
                        >> > I use
                        >> > function LZ(x) { return (x<0||x>=10?"": "0") + x }[/color]
                        >>
                        >> Which is good, probably optimal -- to be improved only by making it a
                        >> prototype :).[/color]
                        >
                        >But allows for a string with extraneous leading zeros:
                        >
                        >function LZ(x) { return (x<0||x>=10?"": "0") + x }
                        >alert(LZ('09') );[/color]

                        As I said : the programmer knows what the parameter will be like. My LZ
                        is for use on Numbers, not on strings. '09' is not a Number, it is a
                        String.

                        In the rare (not happened yet) case that the item to be processed by LZ
                        is or might be a string, I'd use LX(+x).

                        To stretch a string, I would use something like
                        function Prfx(Q, L, c) { var s = Q+"" // ??
                        // if (!c) var c = ' '
                        if (c.length>0) while (s.length<L) { s = c+s } ;
                        return s }

                        --
                        © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                        Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                        Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                        Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                        Comment

                        • rh

                          #13
                          Re: adding 2 times together

                          Grant Wagner wrote:[color=blue]
                          > rh wrote:
                          >[color=green][color=darkred]
                          > > > > x = x < 10 ? "0" + +x : "" +x;[/color][/color][/color]
                          <...>[color=blue]
                          >
                          > But allows for a string with extraneous leading zeros:
                          >[/color]

                          Actually, as intended though. It was a dubious attempt to match the
                          behaviour string input to an expression given by JRS -- in which it
                          turns out, he had no intention of allowing strings as input. So, time
                          to chuckle, perhaps, and move on.

                          However, I think I may ask for the criteria next time, including what
                          is meant by "optimal" ;-)

                          ../rh

                          Comment

                          • rh

                            #14
                            Re: adding 2 times together

                            Dr John Stockton wrote:
                            [color=blue]
                            > JRS: In article <290e65a0.04092 91834.3ca8bf2b@ posting.google. com>,
                            > dated Wed, 29 Sep 2004 19:34:50, seen in news:comp.lang. javascript, rh
                            > <codeHanger@yah oo.ca> posted :
                            >[color=green]
                            > > But perhaps in a typeless language, in the overwhelming
                            > >majority of cases, it shouldn't be necessary for the programmer to
                            > >differentiat e between the two.[/color]
                            >
                            > It is trivial, efficient, and not necessary.
                            >[color=green]
                            > > If it is, then it seems most sensible
                            > >to present the utility a prototype of the core object (not that you've
                            > >suggested anything to the contrary).[/color]
                            >
                            > To suit all cases, ISTM that it would need to be added to String and
                            > Number. It's briefer to use LZ(D.getDate()) than D.getDate().LZ( ), too!
                            >[/color]

                            LZ is simply a case in point.

                            To me, it's much more a matter of an attempt to match the language,
                            because in providing recommended service utilities you're really
                            extending the language beyond what is provided in the base.

                            So, the two choices I see are tightly couple to a type through
                            prototype, or write a function that isn't tied to a type and provides
                            reasonable output based on "reasonable " input.

                            After all, it's this sort of flexibility in the language that allows
                            you to write such things as you have, e.g.:

                            '0'.substring(X >=10)

                            where the substring parameter is a logical value, yet you get a
                            well-defined and reasonable result (through implicit coercion to the
                            type the method actually understands). The same could be done with LZ,
                            with little or no cost in efficiency, when called with an integer
                            type.

                            Even if the decision is to prototype, the function could be made
                            common to the types that it supports.

                            <...>
                            [color=blue][color=green]
                            > >Somewhat surprisingly, it appears not to be.[/color]
                            >
                            > It would become
                            > function addZero(x) { if (x.length < 2) x = '0' + x ; return x }
                            >
                            > function addZero(x) { return x.length < 2 ? '0' + x : x }
                            >
                            > is perhaps better, though.
                            >[color=green]
                            > > And that's what I meant
                            > >when saying "optimal" is hard to achieve as it depends on which JS
                            > >engine is performing the computation. Outside IE, computation
                            > >efficiency of that expression in several of the more popular browsers
                            > >(even with String() omitted) ranges in my tests from slow to dismal.[/color]
                            >
                            > In comparison with ???[/color]

                            A number of others given in the earlier posts.
                            [color=blue]
                            >[color=green]
                            > >The point is that it is non-trivial to assess computational efficiency
                            > >by simply looking at the operations in an expression.[/color]
                            >
                            > Indeed. The easiest way is to post it here, claim it as good, and wait
                            > for results.[/color]

                            Ah, yes, see who takes the bait! ;-)

                            ../rh

                            Comment

                            • Dr John Stockton

                              #15
                              Re: adding 2 times together

                              JRS: In article <290e65a0.04093 01535.2b7adda9@ posting.google. com>,
                              dated Thu, 30 Sep 2004 16:35:08, seen in news:comp.lang. javascript, rh
                              <codeHanger@yah oo.ca> posted :[color=blue]
                              >
                              >However, I think I may ask for the criteria next time, including what
                              >is meant by "optimal" ;-)[/color]

                              As a practical definition, any member of the set of solutions that
                              cannot be shown to be non-optimal, "cannot" being judged by "has not".

                              --
                              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                              Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
                              PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
                              Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

                              Comment

                              Working...