简体   繁体   English

jQuery UI Datepicker的天数差异

[英]jQuery UI Datepicker difference in days

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 . 我尝试使用weekNumberPicked - weekNumberCurrent进行计算,但是如果两个日期位于不同的年份,则结果不正确,因此我可能需要像daysDifference / 7这样得到它。 How should I implement this with the onSelect action? 我应该如何使用onSelect动作来实现呢?

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

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;

difference now 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;

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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM