javascript jQuery UI Datepicker 天数差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5142693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:08:06  来源:igfitidea点击:

jQuery UI Datepicker difference in days

javascriptjqueryjquery-uidate

提问by Petya petrov

I need to calculate the number of weeks difference between the chosen date and the current date. I've tried to calculate with weekNumberPicked - weekNumberCurrent, but if the two dates are in different years, the result is incorrect, so I probably need to get it like daysDifference / 7. How should I implement this with the onSelectaction?

我需要计算所选日期与当前日期之间的周数差异。我试图用 计算weekNumberPicked - weekNumberCurrent,但如果两个日期在不同的年份,结果是不正确的,所以我可能需要像daysDifference / 7. 我应该如何通过onSelect操作来实现这一点?

回答by Joakim Johansson

You can use the Datepicker's function getDate to get a Date object.

您可以使用 Datepicker 的函数 getDate 来获取 Date 对象。

Then just subtract one date from the other (might want to get the absolute value as well) to get the milliseconds in difference, and calculate the difference in days, or weeks.

然后只需从另一个日期中减去一个日期(也可能想要获得绝对值)以获得差异的毫秒数,并计算天数或周数的差异。

$('#test').datepicker({
    onSelect: function() {
        var date = $(this).datepicker('getDate');
        var today = new Date();
        var dayDiff = Math.ceil((today - date) / (1000 * 60 * 60 * 24));
    }
});

回答by krtek

Since DatePicker getDate() methode returns a javascript Date object, you can do something like :

由于 DatePicker getDate() 方法返回一个 javascript Date 对象,您可以执行以下操作:

var myDate = $('.datepicker').datepicker('getDate');
var current = new Date();
var difference = myDate - current;

differencenow contains the number of milliseconds between your two dates , you can easily compute the number of weeks :

difference现在包含两个日期之间的毫秒数,您可以轻松计算周数:

var weeks = difference / 1000 / 60 / 60 / 24 / 7;

回答by ZooboMe23

try this code and applied it to your work :D

尝试此代码并将其应用于您的工作:D

$("#date_born").datepicker({
    onSelect: function () {
        var start = $('#date_born').datepicker('getDate');
        var end   = new Date();
        var age_year   = Math.floor((end - start)/31536000000);
        var age_month   = Math.floor(((end - start)% 31536000000)/2628000000);
        var age_day   = Math.floor((((end - start)% 31536000000) % 2628000000)/86400000);
        $('#age').val(age_year +' year ' + age_month + ' month ' + age_day + ' day');
    },
    dateFormat: 'dd/mm/yy',
    maxDate: '+0d',     
    yearRange: '1914:2014',
    buttonImageOnly: false,
    changeMonth: true,
    changeYear: true
});

Html Code:

html代码:

Date <input type="text" name="date_born" id="date_born"/> 
Age <input type="text" name="age"  id="age" />