0

I am using this code in order to countdown a date:

function countdown()
{
    var now = new Date();
    var end = new Date('Mars 13, 2016 13:12:12'),

    $.each(times, function( key, value ) {
        var left = end - now;
        var days = Math.floor( left / (1000 * 60 * 60 * 24) );
        var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
        var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
        var seconds = Math.floor( (left % (1000 * 60)) / 1000 );

        displayTime = '';
        if (days > 0) {
            displayTime = days+' days';
        }
        displayTime = displayTime + ' ' +hours+' Hours ' + minutes+' Minutes ' + seconds+'s';

        $('#cont'+value.id).text(displayTime)
    });

}

But it doesn't counts it properly since it is not considering if month have 31 days, 28/29 days ...

And the second thing is that when it reaches the expiring date, It does not stops and continues to count down below zero.

What have i done wrong, and how to fix it please ?

Venkat.R
  • 7,420
  • 5
  • 42
  • 63
Jis Maxi
  • 226
  • 1
  • 4
  • 16
  • No reason to calculate this yourself, look at http://www.w3schools.com/js/js_date_methods.asp to use the built in date methods. – jmiraglia Dec 15 '16 at 03:31
  • Any example ? i didn't found that on your link. – Jis Maxi Dec 15 '16 at 03:35
  • I believe part of your problem is you aren't using UTC dates. Checkout this answer here: http://stackoverflow.com/a/15289883/407526 .. Also curious why month counts would matter in your example since you are displaying amount of "months" until ... – Adrian Dec 15 '16 at 03:41
  • how does days get screwed up with 31/29/28??? Does not make any sense... – epascarello Dec 15 '16 at 03:44
  • @Aliester i want the same date format i used in this example and with time. – Jis Maxi Dec 15 '16 at 03:47
  • 2
    Try http://momentjs.com/ if project allows – Venkat.R Dec 15 '16 at 03:54
  • My script work well, i want solve only the little problem of month only, i don't want to use another library. – Jis Maxi Dec 15 '16 at 16:27
  • @jmiraglia—please do not reference w3schools, the site is full of errors. Either reference the language specification or MDN. – RobG Dec 17 '16 at 02:04
  • The code you've posted is unrelated to the errors you report. You should post your code as a runnable snippet that actually demonstrates the issue. You don't show how the function is called, there should be a setTimeout or setInterval somewhere. Also, what is *times* and why is *displayTime* global? Lastly, do not parse strings with the Date constructor, pass the arguments as values `new Date(2016, 2,13, 13, 12,12)` – RobG Dec 17 '16 at 02:27
  • @Aliester—UTC dates are irrelevant, the OP is doing everything as "local". – RobG Dec 17 '16 at 02:30
  • @RobG the format you suggested do not work, it return NaN ... – Jis Maxi Dec 17 '16 at 07:30
  • @JisMaxi—copied and pasted into the console, it creates a Date for 31 March 2016 at 13:12:12 in the host time zone. You may have mistyped. – RobG Dec 17 '16 at 07:54

2 Answers2

1

The way that I do countdowns is to create a countdown initiation script called countdown.js, and then include this script in your main page with the script tag's src="countdown.js"

Here is the code for countdown.js

CountDownTimer('12/25/2016 12:0 AM', 'countdown');
//CountDownTimer('02/20/2012 10:1 AM', 'newcountdown');

function CountDownTimer(dt, id)
{
    var end = new Date(dt);

    var _second = 1000;
    var _minute = _second * 60;
    var _hour = _minute * 60;
    var _day = _hour * 24;
    var timer;

    function showRemaining() {
        var now = new Date();
        var distance = end - now;
        if (distance < 0) {

            clearInterval(timer);
            document.getElementById(id).innerHTML = 'Merry Christmas!';

            return;
        }
        var days = Math.floor(distance / _day);
        var hours = Math.floor((distance % _day) / _hour);
        var minutes = Math.floor((distance % _hour) / _minute);
        var seconds = Math.floor((distance % _minute) / _second);

        if(hours < 10){
          hours = "0"+hours;
        }
        if(minutes < 10){
          minutes = "0"+minutes;
        }
        if(seconds < 10){
          seconds = "0"+seconds;
        }

        document.getElementById(id).innerHTML = "<span id='daycount'>" + days + ' days</span><br/>';
        document.getElementById(id).innerHTML += hours + ':';
        document.getElementById(id).innerHTML += minutes + ':';
        document.getElementById(id).innerHTML += seconds + '';
    }

    timer = setInterval(showRemaining, 1000);
}

Now on your main page

Include the countdown script with <script src="countdown.js"></script> in your <head>.

Then create a div with id="countdown".

The countdown div's id is defined by the first line of the countdown.js script, as the second function input for CountDownTimer();.

My code is set to count down to christmas, you change change this date and time easily by modifying the first line of countdown.js to suit your date needs. Make sure you use the same format as the supplied date though! mm/dd/yyyy H:m AM/PM

pattyd
  • 5,927
  • 11
  • 38
  • 57
  • 1
    Aww, you made this too easy for him. GJ though. – jmiraglia Dec 15 '16 at 04:55
  • Still have the same problem, nothing changed ... one day of difference (my script work in the same way as yours , i don't have problem using it ... i just want to solve the problem of months). – Jis Maxi Dec 15 '16 at 16:25
  • @JisMaxi what is your computer's time set to? Javascript uses the time of the client machine viewing the page, so it would depend on the system time. Check the clock on your computer and set it to the right date, if it isn't already? – pattyd Dec 17 '16 at 23:24
0

You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing). Either write a small function yourself or use a library.

Also, if your code depends on a particular library, you should include a tag for that. There are many posts here on how to create a timer.

The code you've posted does not have any months so it's unclear why you're having an issue with them. Perhaps you want to count down years, moths, days, etc.? That's a much more difficult issue than just days, hours, etc. and there are questions and answers for that too.

var countDown = (function() {
  var endDate;
  
  return function(eDate) {
    endDate = endDate || eDate;
    var msg = '';
    var now = Date.now();
    var r = endDate - now;
    var d, h, m, s;
    
    if (r <= 1000) {
      msg = 'Finished!';

    } else {
      d = r / 8.64e7 | 0;
      h = r % 8.64e7 / 3.6e6 | 0;
      m = r % 3.6e6  / 6e4 | 0;
      s = r % 6e4 / 1000 | 0;
      msg = (d? d + ' day' + (d == 1? '':'s') + ', ' : '') +
            h + ' hour' + (h==1?'':'s') + ', ' + 
            m + ' minute' + (m==1?'':'s') + ' and ' + 
            s + ' second' + (s==1?'':'s');
    }
    document.getElementById('counter').textContent = msg;
    var lag = 1010 - (Date.now() % 1000);

    if (r > 0) {
      setTimeout(countDown, lag);
    }
  }
}());

countDown(new Date(2016,11,25));
<span id="counter"></span>
Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209