Brandrally Brandrally - 2 months ago 19
Javascript Question

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 startdate 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>

<input name="expires" type="text" id="expires" readonly/>

Answer

Sometimes what looks like quite a straight forward task becomes quite complicated.

 $(document).ready( function () {

    $("#registerfor, #startdate").change( function () {

        var str = $("#startdate").val();

        if( /^\d{2}\/\d{2}\/\d{4}$/i.test( str ) ) {

            var parts = str.split("/");

            var day = parts[0] && parseInt( parts[0], 10 );
            var month = parts[1] && parseInt( parts[1], 10 );
            var year = parts[2] && parseInt( parts[2], 10 );
            var duration = parseInt( $("#registerfor").val(), 10);

            if( day <= 31 && day >= 1 && month <= 12 && month >= 1 ) {

                var expiryDate = new Date( year, month - 1, day );
                expiryDate.setFullYear( expiryDate.getFullYear() + duration );

                var day = ( '0' + expiryDate.getDate() ).slice( -2 );
                var month = ( '0' + ( expiryDate.getMonth() + 1 ) ).slice( -2 );
                var year = expiryDate.getFullYear();

                $("#expires").val( day + "/" + month + "/" + year );

            } else {
                // display error message
            }
        }
    });
});

Here is a fiddle so you can see it in action.

Comments