JQuery Datepicker - Add Years

余生长醉 提交于 2019-12-14 02:28:24

问题


I have added the JQuery Datepicker control to one of my ASP.Net pages. The page allows a user to add details about a piece of equipment.

They can also select the date they bought the equipment using the Datepicker, then from a drop down list, select the warranty length (ie, 1,2,3,4,5 years etc) that comes with the equipment. Based on the warranty length they have selected, I need JQuery code to work out the date the warranty will expire for the Equipment, ie, if bought 21/02/2011, 3 year warrenty, then warranty expires 21/02/2014.

I have looked at the other Datepicker examples on this site, but none seem to show how to add years to a date, rather just how to add days.

This is my code so far

$('#equipment_purchaseDate').datepicker({ dateFormat: 'dd/mm/yy', onSelect: function (dateStr) {
        var d = $.datepicker.parseDate('dd/mm/yy', dateStr);
        d.setDate(d.getDate() + ($('#equipment_warrantyLength').val() * 365)); //multiple warranty length by 365 to get years, then add to startDate
        $('#equipment_warrentyExpires').datepicker('setDate', d);
    } 
});

However this doesn't seem to be working correctly.

Any feedback would be much appreciated.

Thanks.


回答1:


Try using Date's setFullYear and getFullYear:

$("#equipment_purchaseDate").datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateStr) {
        var d = $.datepicker.parseDate('dd/mm/yy', dateStr);
        var years = parseInt($("#equipment_warrantyLength").val(), 10);

        d.setFullYear(d.getFullYear() + years);

        $('#equipment_warrentyExpires').datepicker('setDate', d);
    }
});

Here's a working example: http://jsfiddle.net/andrewwhitaker/Dvd5C/




回答2:


You probably have to define the datetime picker for the other field:

$('#equipment_warrentyExpires').datepicker({ dateFormat: 'dd/mm/yy' });
$('#equipment_purchaseDate').datepicker({ dateFormat: 'dd/mm/yy', 
  onSelect: function (dateText, inst) {
      alert(dateText);
  var d = $.datepicker.parseDate('dd/mm/yy', dateText);
      alert(d);
  d.setDate(d.getDate() + ($('#equipment_warrantyLength').val() * 365)+1); 
  //multiple warranty length by 365 to get years, then add to startDate
  $('#equipment_warrentyExpires').datepicker('setDate', d);
  } 
});

I've changed it slightly.




回答3:


var incrementmonth = $("#<%=calPlannedCompletionDate.ClientId%>").datepicker('getDate', +12m');
incrementmonth.setMonth(incrementmonth.getMonth() + 12);
$("#<%=calPlannedCompletionDate.ClientId%>").datepicker('setDate', incrementmonth);


来源:https://stackoverflow.com/questions/5067765/jquery-datepicker-add-years

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!