4

I'm creating a countdown Timer that counts down to a date that is inputted in the code for example April 6th 2016.

So far I have got it to output the amount of days, but I cannot figure out how to do the amount of months and years. I do not need Hours Minutes or seconds!

code in app.js

$(document).ready(function(){
    eventTime = '6 April 2016';
})

Code in countdown.js:

(function($){
$.fn.countdown = function(options) {

    var settings = { date: null };

    if (options) {
        $.extend(settings, options);
    }

    this_sel = $(this);

    function count_exec () {
        eventDate = Date.parse(settings['date']) / 1000;
        currentDate = Math.floor($.now () / 1000);

        seconds = eventDate - currentDate

        days = Math.floor(seconds / (60 * 60 * 24));
        months = Math.floor(seconds / (60 * 60 * 12));
        alert(days);
    }   

    count_exec();
}
})(jQuery);
Tom Withers
  • 1,171
  • 4
  • 16
  • 28

1 Answers1

3

Given two dates, use the following code to compute their difference in milliseconds, then in seconds, minutes, hours, days and months:

var currentDate = new Date();
var eventDate = new Date(2016, 3, 6); // months start from 0
var milliseconds = eventDate.getTime() - currentDate.getTime();
var seconds = parseInt(milliseconds / 1000);
var minutes = parseInt(seconds / 60);
var hours = parseInt(minutes / 60);
var days = parseInt(hours / 24);
var months = parseInt(days / 30);
seconds -= minutes * 60;
minutes -= hours * 60;
hours -= days * 24;
days -= months * 30;

For a more accurate difference in months, take a look at Difference in Months between two dates in JavaScript.

Community
  • 1
  • 1
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34