Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery / Javascript - Add years to date variable

I have a small trouble that would be great to have some help with. I am creating a small form that I want to take a current date formatted 'dd/mm/yyyy' and add a year(s) variable from a drop-down box to create a final expiry date. The only trouble is that I do not know how to parse the start-date as a date variable in order to complete the calculation. Any thoughts or help would be greatly appreciated. Paul.

<script>
    $(document).ready(function () {
        $("#registerfor, #startdate, ").change(function () {
            // Get Variables
            var startdate = $("#startdate").val();
            var registerfor = $("#registerfor").val();
            // Add Years to Date
            var expirydate = startdate + registerfor;
            // Send Result on
            $("#expires").val(expirydate);
        });
    });
</script>
<input name="startdate" id="startdate" value="dd/mm/yyyy" />
<select id="registerfor" name="registerfor">
    <option value="1">1 Year</option>
    <option value="2">2 Years</option>
    <option value="3">3 Years</option>
</select>
like image 981
Brandrally Avatar asked Feb 04 '13 11:02

Brandrally


1 Answers

A quick and easy solution :

var myDate = new Date();
myDate.setFullYear(myDate.getFullYear() + nbYearsToAdd);

"nbYearsToAdd" can be negative.

like image 63
Christophe P Avatar answered Sep 17 '22 11:09

Christophe P