JavaScript Counter – Count Days Hours Minutes Seconds

I keep getting requests and I can’t help but post another JavaScript related counter! As always, in case of any issues/doubts/suggestions or you just want to appreciate, feel free to leave a comment.


Javascript Counter to Count Days Hours Minutes Seconds –

This script is very simple; it takes a date to count the time from/to, an ID to put the timer in. To be very precise, this counter shows the total number of 24 hours intervals between the date-time given and current date-time. It is also possible to have more than one timer on a page. Demo page.

JavaScript Day, Hours, Minutes, Seconds Counter – This works with past as well as future days. If a future date is used, it acts as a countdown timer and when the date is reached it just rolls over and acts as a countup timer.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JavaScript Days-Hours-Minutes-Seconds Counter - Praveen Lobo</title>
<script type="text/javascript">
/**********************************************************************************************
* Days-Hours-Minutes-Seconds Counter script by Praveen Lobo 
* (http://PraveenLobo.com/techblog/javascript-counter-count-days-hours-minutes-seconds/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function DaysHMSCounter(initDate, id){
    this.counterDate = new Date(initDate);
    this.container = document.getElementById(id);
    this.update();
}

DaysHMSCounter.prototype.calculateUnit=function(secDiff, unitSeconds){
    var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
    return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}

DaysHMSCounter.prototype.calculate=function(){
    var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
    this.days = this.calculateUnit(secDiff,86400);
    this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
    this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
    this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}

DaysHMSCounter.prototype.update=function(){ 
    this.calculate();
    this.container.innerHTML =
        " <strong>" + this.days + "</strong> " + (this.days == 1? "day" : "days") +
        " <strong>" + this.hours + "</strong> " + (this.hours == 1? "hour" : "hours") +
        " <strong>" + this.mins + "</strong> " + (this.mins == 1? "min" : "mins") +
        " <strong>" + this.secs + "</strong> " + (this.secs == 1? "sec" : "secs");
    var self = this;
    setTimeout(function(){self.update();}, (1000));
}

window.onload=function(){ new DaysHMSCounter('January 01, 2000 00:00:00', 'counter'); }

</script>
</head>
<body>
<div id="counter">Contents of this DIV will be replaced by the timer</div>
</body>
</html>
This entry was posted in JavaScript and tagged , , , , , , , . Bookmark the permalink.

19 Responses to JavaScript Counter – Count Days Hours Minutes Seconds

  1. That is very attention-grabbing, You are an overly professional blogger. I’ve joined your rss feed and look forward to in search of more of your wonderful post. Additionally, I’ve shared your site in my social networks

  2. Tristan says:

    Hey, cool script. I’m trying isolate just the counting up seconds. A friend is making a site that shows their age in seconds and their position live on a map. Could you shoot me across that code? Thanks in advance, great blog.

    • Lobo says:

      That should be pretty simple for you to figure out.

      Change calculate method to store secDiff as this.secs and remove all other lines.
      Change the update method to show only the seconds by assigning it to innerHTML.

      Try it out.

  3. Van says:

    Hi

    Thanks for the script :) I wanted to ask is possible to change/specify the time zone? I need the counter to be set for London GMT.

    Any help would be appreciated
    Thank you
    Regards
    Van

  4. Van says:

    Hi again

    I just figured out that the script pulls the time from the users machine, so the timezone will be shown in the output.

    Thanks mate

    Van

  5. marcio says:

    I want to put a website when the times out ….its possible?

  6. John Watt says:

    Hey Lobo, I came back to your site again after two years. Thanks for your help from before. I would like to use the above “Javascript Counter to Count Days Hours Minutes Seconds”, but I was wondering if you could modify the code so that there is a leading zero in front of any single digit seconds, minutes, hours…. (and maybe even days).
    So this:
    234 days, 8 hours, 5 minutes, and 3 seconds
    becomes:
    234 days, 08 hours, 05 minutes, and 03 seconds
    Your code is the best so far, but I think double digit seconds (and mins, hrs, days) would be a nice improvement. If you get around to it, thanks. If not, thanks anyway.

    • John Watt says:

      I basically would like the code from Javascript Countdown Timer, but have it so that the Years and Months are converted into Days. That code already has the leading zeros for the seconds, minutes, and hours; although I think having a leading zero in front of single digit days would make it even better.

    • John Watt says:

      Nevermind. I think that I may have successfully modified the script to do what I wanted. I basically just combined elements from both scripts and it seems to be working now. Here it is, if anyone wants leading zeros in front of their single digit days, hours, minutes, and seconds.

      function CountDown(initDate, id){
      this.endDate = new Date(initDate);
      this.countainer = document.getElementById(id);
      this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
      this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
      this.hours = 0, this.minutes = 0, this.seconds = 0;
      this.updateNumOfDays();
      this.updateCounter();}

      CountDown.prototype.updateNumOfDays=function(){
      var dateNow = new Date();
      var currYear = dateNow.getFullYear();
      if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {this.numOfDays[1] = 29;}
      var self = this;
      setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));}

      CountDown.prototype.datePartDiff=function(then, now, MAX){
      var diff = now - then - this.borrowed;
      this.borrowed = 0;
      if ( diff > -1 ) return diff;
      this.borrowed = 1;
      return (MAX + diff);}

      CountDown.prototype.calculate=function(){
      var futureDate = this.endDate;
      var currDate = new Date();
      this.seconds = this.datePartDiff(currDate.getSeconds(), futureDate.getSeconds(), 60);
      this.minutes = this.datePartDiff(currDate.getMinutes(), futureDate.getMinutes(), 60);
      this.hours = this.datePartDiff(currDate.getHours(), futureDate.getHours(), 24);

      this.days = this.datePartDiff(currDate.getDate(), futureDate.getDate(), this.numOfDays[futureDate.getMonth()]);

      this.months = this.datePartDiff(currDate.getMonth(), futureDate.getMonth(), 12);

      this.years = this.datePartDiff(currDate.getFullYear(), futureDate.getFullYear(),0);}

      CountDown.prototype.addLeadingZero=function(value){
      return value (new Date()) ) {
      var self = this;
      setTimeout(function(){self.updateCounter();}, 1000);}}

      window.onload=function(){new CountDown('December 20, 2013 00:00:00', 'counter');}

       

      • John Watt says:

        Disregard the above code. I tried posting my code, but it didn’t post right, and there are a lot of parts missing. I”m not sure why.

    • John Watt says:

      I’m going to try posting it again without the code tags.

      /**********************************************************************************************
      * Days-Hours-Minutes-Seconds Counter script by Praveen Lobo
      * (http://PraveenLobo.com/techblog/javascript-counter-count-days-hours-minutes-seconds/)
      * This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
      * http://praveenlobo.com/blog/disclaimer/
      **********************************************************************************************/

      function Countdown(initDate, id){
      this.counterDate = new Date(initDate);
      this.container = document.getElementById(id);
      this.update();}

      Countdown.prototype.calculateUnit=function(secDiff, unitSeconds){
      var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
      return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));}

      Countdown.prototype.calculate=function(){
      var secDiff = Math.abs(Math.round(((new Date()) – this.counterDate)/1000));
      this.days = this.calculateUnit(secDiff,86400);
      this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
      this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
      this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);}

      Countdown.prototype.addLeadingZero=function(value){
      return value < 10 ? ("0" + value) : value;}

      Countdown.prototype.formatTime=function(){
      this.secs = this.addLeadingZero(this.secs);
      this.mins = this.addLeadingZero(this.mins);
      this.hours = this.addLeadingZero(this.hours);
      this.days = this.addLeadingZero(this.days);}

      Countdown.prototype.update=function(){
      this.calculate();
      this.formatTime();
      this.container.innerHTML =
      this.days + (this.days == 1? " Days, " : " Days, ") +
      this.hours + (this.hours == 1? " Hours, " : " Hours, ") +
      this.mins + (this.mins == 1? " Minutes, " : " Minutes, ") +
      this.secs + (this.secs == 1? " Seconds" : " Seconds");
      var self = this;
      setTimeout(function(){self.update();}, (1000));}

      window.onload=function(){ new Countdown('January 01, 2014 00:00:00', 'counter'); }

       

      • John Watt says:

        Okay, the above code seems to be accurate. This is what you need if you always want double digit seconds, minutes, hours, and days in your countdown.

        So now you will have “04 days, 09 hours, 01 minutes, and 04 seconds” instead of “4 days, 9 hours, 1 minutes, and 4 seconds”.

  7. emmy says:

    pls can body help . i need a count down time left for my login page for internet users. am running a hotspot internet access. thank u emmy

  8. Dheeraj says:

    Hi, can you pl make it like in this format
    07 years 523 days 03 hours 07 mins 05 secs
    Currently there year and 0 are mising in this blog..
    pl edit the code, i need it, pl mail me if you can..

  9. Ravi Jain says:

    Very nice blog………….thanks for share this code.

  10. smritee says:

    when i use this code

    var serverTime=new Date(”);
    var secDiff = Math.abs(Math.round(((serverTime) – this.counterDate)/1000));
    count up not working,

    how to solve that

  11. smritee says:

    var serverTime=new Date(”);
    var secDiff = Math.abs(Math.round(((serverTime) – this.counterDate)/1000));

  12. Masta Koda says:

    Excellent script – Thank you. Saved me writing my own!

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + one =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.