Announcement

Collapse
No announcement yet.

countup timer

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

  • countup timer

    I had this novel idea.
    On my homepage where it describes me, I'd like to say I'm currently 19 yrs 4 months 2 weeks 1 day 5 hours 50 minuts 49 seconds
    and have said javascript code update every 1 second. It would keep counting from a locked number I plug in.

    I'm kinda new to Java, but know other similar languages...
    I can live without it, but it'd be nifty. Any ideas where I can find such code?

  • #2
    You need my ElapsedTime constructor:
    [code]

    <script language="Javascript">
    function ElapsedTime(inFromDate,inToDate) {
    var inFromDate = (arguments.length == 0) ? new Date() : arguments[0];
    var inToDate = (arguments.length == 1) ? new Date() : arguments[1];

    // if (arguments.length == 0) var inFromDate = new Date(); // IE4 has a bug in constructors,
    // if (arguments.length == 1) var inToDate = new Date(); // so use above method.

    var fromDate = new Date(inFromDate);
    var toDate = new Date(inToDate);

    var tempDate = new Date();
    if (fromDate.getTime() > toDate.getTime()) {
    tempDate = new Date(fromDate);
    fromDate = new Date(toDate);
    toDate = new Date(tempDate);
    }
    var totMonths = 12*toDate.getFullYear() + toDate.getMonth() +
    -12*fromDate.getFullYear() - fromDate.getMonth()
    var years = Math.floor(totMonths / 12)
    var months = totMonths - 12*years
    if (dateAsNumber(toDate,"D") < dateAsNumber(fromDate,"D")) months -= 1
    if (months < 0) {
    months = 0
    if (years > 0) years -= 1
    }

    var yearsOff = years + fromDate.getFullYear()
    var monthsOff = months + fromDate.getMonth()
    if (monthsOff >= 12) {
    monthsOff -= 12
    yearsOff += 1
    }
    var tempDate = new Date(fromDate);
    tempDate.setFullYear(yearsOff);
    tempDate.setMonth(monthsOff); // might push us into early next month, so...
    while (tempDate.getDate() < fromDate.getDate() && tempDate.getDate() < 9 )
    tempDate.setTime(tempDate.getTime() - 1000*60*60*24); // Feb 29 etc.

    var milliSecs = toDate.getTime() - tempDate.getTime();
    var oneSecond = 1000;
    var oneMinute = 60 * 1000;
    var oneHour = 60 * oneMinute;
    var oneDay = 24 * oneHour;
    var oneWeek = 7 * oneDay;
    var weeks = Math.floor(milliSecs / oneWeek);
    milliSecs -= weeks * oneWeek;
    var days = Math.floor(milliSecs / oneDay);
    milliSecs -= days * oneDay;
    var hours = Math.floor(milliSecs / oneHour);
    milliSecs -= hours * oneHour;
    var minutes = Math.floor(milliSecs / oneMinute);
    milliSecs -= minutes * oneMinute;
    var seconds = Math.floor(milliSecs / oneSecond);

    var timeValue = "";
    if (years) timeValue += years + ((years==1) ? " year, " : " years, ");
    if (months) timeValue += months + ((months==1) ? " month, " : " months, ");
    if (weeks) timeValue += weeks + ((weeks==1) ? " week, " : " weeks, ");
    if (days) timeValue += days + ((days==1) ? " day, " : " days, ");
    var timeValueDays = timeValue.substring(0 , timeValue.length - 2);
    timeValue += hours + ((hours==1) ? " hour, " : " hours, ");
    timeValue += minutes + ((minutes==1) ? " minute, and " : " minutes, and ");
    timeValue += seconds + ((seconds==1) ? " second " : " seconds ");

    this.years = years;
    this.months = months;
    this.weeks = weeks;
    this.days = days;
    this.hours = hours;
    this.minutes = minutes;
    this.seconds = seconds;
    this.text = timeValue;
    this.textDays = timeValueDays;
    }

    function dateAsNumber(inDate,inWhat) {
    var what = "", yearBit = 0, monthBit = 0
    if (typeof(inWhat) == "undefined" || inWhat.toString() == "" || inWhat.toString() == null) inWhat = ""
    what = inWhat.toString().toUpperCase()
    if (what != "M" && what != "D") // we want yyyy bit
    yearBit = inDate.getFullYear() * Math.pow(10,13);
    if (what != "D") // we want month bit
    monthBit = inDate.getMonth() * Math.pow(10,11);
    return yearBit +
    monthBit +
    inDate.getDate() * Math.pow(10,09) +
    inDate.getHours() * Math.pow(10,07) +
    inDate.getMinutes() * Math.pow(10,05) +
    inDate.getSeconds() * Math.pow(10,03) +
    inDate.getMilliseconds()
    }

    // To invoke it, (remembering that in Java Dates,
    // months go from 0 (Jan) to 11 (Dec) [If I ever meet that guy...] )

    function ageClock() {
    var leaveDate = new Date(1980,11,25) // for December 25, 1980
    var now = new Date();
    var elapsed = new ElapsedTime(leaveDate,now);
    document.forms.personal.age.value = elapsed.text;
    }

    window.onload = function anonymous() { setInterval("ageClock()",1000) }
    </script>

    <form name=personal>
    Age: <input type=text size=30 name=age>
    </form>
    Jon Hanlon

    Comment


    • #3
      Alright!..

      It works like a charm but I'd like to expand the function.
      As soon as I ask my parents what time of the day they think they remember I was born, I want to control it down to the second. Right now it assumes I was born at 00:00 hours, insofar as that user's computer is concerened. Is there a small part I can change easily to add that precise control?


      P.S. ROFL regarding 0 (Jan) to 11 (Dec)
      // To invoke it, (remembering that in Java Dates,
      // months go from 0 (Jan) to 11 (Dec) [If I ever meet that guy...] )
      I know the feeling. I spent a solid minute laughing in knowing agreement.
      I have a similar beef with Visual Basic. False is = to 0. Fine. True is = to -1. Where DOES THAT COME FROM?!! Dang Microsoft...

      Comment


      • #4
        The Date constructor takes several formats:

        new Date("Month dd, yyyy")
        new Date("Month dd, yyyy hh:mm:ss")
        new Date(yyyy,mm,dd)
        new Date(yyyy,mm,dd[,hh[,mm[,ss[,mmm]]]])
        new Date(millsecondsSince1970)

        So use
        new Date("August 12, 1983 13:23:00")
        or
        new Date(1983,7,12,13,23,0)
        or
        new Date("September 3, 1984 9:15")
        or
        new Date(1984,8,3,9,15)
        etc.

        In VB, True is -1 due to the binary representation. In 2's complement notation, zero is 00000000000000000000000000000000, one is 00000000000000000000000000000001, and minus one is
        11111111111111111111111111111111. So you see that the difference between one and zero is a single bit. In other words, if we used one for true and had a single bit flip on us then the result would be negated. The other problem is the way that Basic does its boolean comparisons like AND.
        If we are doing a bitwise comparison, then we want all '1's in our 'true' field. So we have
        true = all(1) = -1
        false = all(0) = 0

        Note that in Javascript, false is zero and true is any other number.
        Jon Hanlon

        Comment


        • #5
          Ex-cel-len-té

          Is there any way I can show this on the HTML page directly... Like instead of in a text field... Make it look like normal text around it... AND... Have said theory work in Netscape 4.x ?

          I'm thinking document.write( call function )

          Comment


          • #6
            document.write() won't work without a hell of a lot of playing about with layers. _mrkite is our resident layer expert, perhaps he could help.

            Personally I feel that NN4 users deserve what they get.
            (Which ain't much.)
            They're used to crappy looking pages, much as vintage car enthusiasts are used to shivering. Both groups suffer for the 'ambiance', so I say let them be. Just don't expect me to go out of my way to cater for the fringe minority.

            Code:
            <script language="Javascript">
            
            function ageClock() { 
              var leaveDate = new Date(1980,11,25,9,20) // for December 25, 1980 9:20am
              var now = new Date(); 
              var elapsed = new ElapsedTime(leaveDate,now); 
              if (document.all) { // IE4+
                  document.all.ageSpan.innerHTML = elapsed.text; 
                  return;
              }
              if (document.getElementById) { // NS6
                  document.getElementById("ageSpan").innerHTML = elapsed.text;
                  return;
              }
              document.forms.personal.age.value = elapsed.text; 
            } 
            
            window.onload = setupAge; // no () here
            
            function setupAge() {
              var ageDiv = "";
              if (document.all) // IE4+
                  ageDiv = document.all.ageDiv;
              if (document.getElementById) // NS6
                  ageDiv = document.getElementById("ageDiv")
              if (ageDiv) ageDiv.innerHTML = "<h2> I am now <span id=ageSpan>"
                                           + "&nbsp;</span> old.</h2>"
              setInterval("ageClock()",1000) } 
            }
            </script> 
            
            <div id=ageDiv>
              <form name=personal> 
              Age: <input type=text size=30 name=age> 
              </form>
            <div>
            Jon Hanlon

            Comment


            • #7
              A pile of those scripts at this link,

              http://www.hotscripts.com/JavaScript...ms/Countdowns/

              Comment


              • #8
                ...was that a compliment?

                "resident layer expert" sounds a bit like "town drunk" (or "Suspected Islamic Terrorist") - oh, well...

                Here's some ambience...

                Code:
                <html>
                <head>
                <title>crappy looking page</title>
                <style type="text/css">
                
                body {margin-top:100px;}
                em {color:#660000;}
                .bodytext {font:200 20px "Times New Roman",serif; color:#453000;}
                #ageDisplay {position:absolute; visibility:hidden;}
                
                </style>
                <script type="text/javascript" language="JavaScript">
                
                function ElapsedTime(inFromDate,inToDate) { 
                var inFromDate = (arguments.length == 0) ? new Date() : arguments[0]; 
                var inToDate = (arguments.length == 1) ? new Date() : arguments[1]; 
                
                // if (arguments.length == 0) var inFromDate = new Date(); // IE4 has a bug in constructors, 
                // if (arguments.length == 1) var inToDate = new Date(); // so use above method. 
                
                var fromDate = new Date(inFromDate); 
                var toDate = new Date(inToDate); 
                
                var tempDate = new Date(); 
                if (fromDate.getTime() > toDate.getTime()) { 
                tempDate = new Date(fromDate); 
                fromDate = new Date(toDate); 
                toDate = new Date(tempDate); 
                } 
                var totMonths = 12*toDate.getFullYear() + toDate.getMonth() + 
                -12*fromDate.getFullYear() - fromDate.getMonth() 
                var years = Math.floor(totMonths / 12) 
                var months = totMonths - 12*years 
                if (dateAsNumber(toDate,"D") < dateAsNumber(fromDate,"D")) months -= 1 
                if (months < 0) { 
                months = 0 
                if (years > 0) years -= 1 
                } 
                
                var yearsOff = years + fromDate.getFullYear() 
                var monthsOff = months + fromDate.getMonth() 
                if (monthsOff >= 12) { 
                monthsOff -= 12 
                yearsOff += 1 
                } 
                var tempDate = new Date(fromDate); 
                tempDate.setFullYear(yearsOff); 
                tempDate.setMonth(monthsOff); // might push us into early next month, so... 
                while (tempDate.getDate() < fromDate.getDate() && tempDate.getDate() < 9 ) 
                tempDate.setTime(tempDate.getTime() - 1000*60*60*24); // Feb 29 etc. 
                
                var milliSecs = toDate.getTime() - tempDate.getTime(); 
                var oneSecond = 1000; 
                var oneMinute = 60 * 1000; 
                var oneHour = 60 * oneMinute; 
                var oneDay = 24 * oneHour; 
                var oneWeek = 7 * oneDay; 
                var weeks = Math.floor(milliSecs / oneWeek); 
                milliSecs -= weeks * oneWeek; 
                var days = Math.floor(milliSecs / oneDay); 
                milliSecs -= days * oneDay; 
                var hours = Math.floor(milliSecs / oneHour); 
                milliSecs -= hours * oneHour; 
                var minutes = Math.floor(milliSecs / oneMinute); 
                milliSecs -= minutes * oneMinute; 
                var seconds = Math.floor(milliSecs / oneSecond); 
                
                var timeValue = ""; 
                if (years) timeValue += years + ((years==1) ? " year, " : " years, "); 
                if (months) timeValue += months + ((months==1) ? " month, " : " months, "); 
                if (weeks) timeValue += weeks + ((weeks==1) ? " week, " : " weeks, "); 
                if (days) timeValue += days + ((days==1) ? " day, " : " days, "); 
                var timeValueDays = timeValue.substring(0 , timeValue.length - 2); 
                timeValue += hours + ((hours==1) ? "hour, " :" hours, "); 
                timeValue += minutes + ((minutes==1) ? " minute, and " : " minutes, and "); 
                timeValue += seconds + ((seconds==1) ? " second" : " seconds"); 
                
                this.years = years; 
                this.months = months; 
                this.weeks = weeks; 
                this.days = days; 
                this.hours = hours; 
                this.minutes = minutes; 
                this.seconds = seconds; 
                this.text = timeValue; 
                this.textDays = timeValueDays; 
                } 
                
                function dateAsNumber(inDate,inWhat) { 
                var what = "", yearBit = 0, monthBit = 0 
                if (typeof(inWhat) == "undefined" || inWhat.toString() == "" || inWhat.toString() == null) inWhat = "" 
                what = inWhat.toString().toUpperCase() 
                if (what != "M" && what != "D") // we want yyyy bit 
                yearBit = inDate.getFullYear() * Math.pow(10,13); 
                if (what != "D") // we want month bit 
                monthBit = inDate.getMonth() * Math.pow(10,11); 
                return yearBit + 
                monthBit + 
                inDate.getDate() * Math.pow(10,09) + 
                inDate.getHours() * Math.pow(10,07) + 
                inDate.getMinutes() * Math.pow(10,05) + 
                inDate.getSeconds() * Math.pow(10,03) + 
                inDate.getMilliseconds() 
                } 
                
                // To invoke it, (remembering that in Java Dates, 
                // months go from 0 (Jan) to 11 (Dec) [If I ever meet that guy...] ) 
                
                function ageClock() { 
                var leaveDate = new Date(1980,11,25) // for December 25, 1980 
                var now = new Date(); 
                var elapsed = new ElapsedTime(leaveDate,now);
                return elapsed.text;
                }
                
                function getElement(id) {
                return document.all ? document.all(id) : 
                document.getElementById ? document.getElementById(id) :
                document.layers ? document.layers[id] : 
                null;
                }
                
                function centerShowIt(id) {
                var winMid, aD = getElement('ageDisplay');
                if (!aD) return;
                if (window.innerWidth) winMid = innerWidth/2;
                else if (document.body) winMid = document.body.clientWidth/2;
                if (!document.layers) {
                aD.style.left = winMid - aD.offsetWidth/2;
                aD.style.visibility = 'visible';
                } else {
                aD.pageX = winMid - aD.clip.width/2;
                aD.visibility = 'show';
                }
                }
                
                function update() {
                var text = ageClock();
                var aD = getElement('ageDisplay');
                if (!aD) return;
                if (!document.layers) {
                aD.innerHTML = text + ';';
                } else {
                aD.document.write('<span class="bodytext">' + text + ';</span>');
                aD.document.close();
                }
                setTimeout('update()',1000);
                }
                
                /* NS4 resize bug fix from webreference.com */
                if (document.layers) {
                origWidth = innerWidth;
                origHeight = innerHeight;
                }
                if (document.layers) window.onresize = function() {
                               if (innerWidth != origWidth || innerHeight != origHeight) 
                               location.reload();
                }
                /********************************************/
                
                window.onload = update;
                
                </script>
                </head>
                <body bgcolor="#eabe83">
                <hr size="8" width="600">
                <div class="bodytext" align="center">
                Well, here's the deal: I may not have learned much about life -<br>
                after all, hard knowing <em>everything</em> when you've only been here for<br>
                <script type="text/javascript" language="JavaScript">
                document.write('<div id="ageDisplay" class="bodytext">');
                document.write(ageClock());
                document.write('</div>');
                centerShowIt('ageDisplay');
                </script>
                <br>but, nevertheless, let me explain to you about the way things are...
                </div>
                <hr size="8" width="600">
                </body>
                </html>
                It's best to put the 'include' on its own line as NS4 Layers don't wrap from one line to the next (they're rectangular inclusions) and, in IE/NS6, the line will jump back & forth as it repaints with different size input; everything gets adjusted (nice layout engine) but it's distracting, at least to my eyes.

                Comment


                • #9
                  New to Java and HTML

                  I might be asking a lot but could someone help me out, Maybe tell me the code for a script to count up days like the one you were talking about in this post, Startin on May 23, 2003, and just continuing up from then, I can't figureo ut how to edit the codes given in this post if maybe someone could input the correct stuff for it for me, I'm not sure how much work that would entail. Thanks.

                  Comment


                  • #10
                    Further implementation

                    Great! I've been searching for a script like this for some days.

                    OK now i'm using _mrkite's code. I need him (or someone) to answer a simple question. I want the script to show just years, months and days (not hours, nor minutes nor seconds). What should i delete?

                    Thank you in advance.

                    Comment


                    • #11
                      http://www.webdeveloper.com/forum/sh...threadid=52530

                      This example is one that updates a page without having to use layers or anything fancy other than the <span> tag, other methods do exist that are just as effective...

                      Comment


                      • #12
                        I have a question for Jon Hanlon:

                        Is there any way to display the years, months, days, hours, minutes and seconds as part of the regular text on a site rather than in a form/text box?

                        Thanks,
                        -Joe

                        Comment


                        • #13
                          Sure is,
                          just create a span and populate its innerHTML.
                          <span id="ticktock"></span>


                          document.getElementById("ticktock").innerHTML = ...
                          Jon Hanlon

                          Comment


                          • #14
                            I also would like to be able to imput this into my web page, but without the form. I would also like to have it formated so that it looks like this:



                            But with years, months, days, hours, minutes and seconds.

                            Is there a way to insert the individual items? This would allow me to format the values many different ways. I am not too good at this type of stuff and would appreciate your help.

                            I will have to say, your script is the best one out there I could find. Most others do not account for leap years and do not display the total elapsed time. May will say how many total years, total weeks, total hours, etc. and do not break it out the way this one does.


                            Jeff

                            Comment


                            • #15
                              Also, have you made any changes to this script? I am currently playing around with the code in your first post. If you have updated any of it, could you post it again?

                              Thanks.
                              Jeff

                              Comment

                              Working...
                              X