使用Datepicker计算年龄范围

时间:2019-07-15 11:49:12

标签: jquery datepicker calculation

如何仅在0-2岁年龄段的日期选择器上显示月份-年份? 如何编写此代码?

For Example:
15 July 2017
15 July 2019
Total: 730 days

1 个答案:

答案 0 :(得分:1)

您可以在Datepicker中设置yearRangeminDatemaxDate,以选择年份范围之间的日期,即2017-2019。即:

$('#d1 , #d2').datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange: '2017:2019', //<--setting range 2 years
    minDate: new Date(2017, 6, 15), //<--min date i.e 15/7/2017
    maxDate: new Date(2019, 6, 15) // <--max date i.e 15/7/2019
});


$(".btn").on("click",function(){
//getting date value from datepicker
var start = $('#d1').datepicker("getDate");
var end = $('#d2').datepicker("getDate");

 var days = (end- start) / (1000 * 60 * 60 * 24);
 console.log(days);
 
$("#total").html("Total  : " +days);

});
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    
       Date1: <input type="text" name="ab" id="d1" />
        <br/>
        Date2: <input type="text" name="ab1" id="d2" />
        <br/>
        <input type="button" value="calculate" class="btn"/>
        
        <div id="total"></div>