tcode
tcode

Reputation: 5105

JQuery Datepicker - Add Years

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.

Upvotes: 1

Views: 16090

Answers (3)

Kavita
Kavita

Reputation: 1

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

Upvotes: 0

LeftyX
LeftyX

Reputation: 35587

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.

Upvotes: 1

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

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/

Upvotes: 5

Related Questions