jQuery计时器天/月/年

时间:2016-01-25 16:45:35

标签: javascript jquery html css

我正在创建倒数计时器,倒计时到代码中输入的日期,例如2016年4月6日。

到目前为止,我已经得到它输出天数,但我无法弄清楚如何做几个月和几年的数量。我不需要几小时或几秒钟!

app.js中的

代码

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

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);

1 个答案:

答案 0 :(得分:2)

给定两个日期,使用以下代码计算它们之间的差异(以毫秒为单位),然后是秒,分钟,小时,天和月:

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;

要想在几个月内获得更准确的差异,请查看Difference in Months between two dates in JavaScript