jQuery

How to add days to date in jQuery

Here Laxmi Kant has explained with an example, How to add days to date in jQuery.
This article will illustrate How to adding days to date in jQuery when enter value in Enter Days field.

In this article you will learn with an example, How to add days to date in jQuery.
This article will illustrate Adding days to given date in jQuery when enter value in Enter Days field.
If you want to get the date by adding days to the start date follow this step.

HTML Markup
The HTML Markup consists of an HTML TextBox type date and number.

<body>
    <label for="date">Enter Date:</label>
    <input type="date" id="startdate" name="date1">
    <label for="enterDays">Enter Days:</label>
    <input type="number" id="adddays" placeholder="Days" />
    <label for="Adddate">After Add Date:</label>
    <input type="text" id="adddate" name="adddate">

</body>

jQuery Code
Inside the jQuery document ready event handler, The change event occurs when the value of an element has been changed then this value will be added at date.

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
        $(document).ready(function () {
            $("#adddays").change(function () {
                var addDays = $("#adddays").val() ? $("#adddays").val() : 0;
                var startDateVal = $("#startdate").val();
                var ModifyInDate = new Date(setDateFormat(startDateVal));
                var NewDate = ModifyInDate.setDate(ModifyInDate.getDate() + parseInt(addDays));
                NewDate = new Date(NewDate);
                if (NewDate != "Invalid Date")
                    $("#adddate").val(setDateFormat(NewDate));


            });


        });
        //This function is used for set date formate
        function setDateFormat(date) {
            DateObj = new Date(date);
            var day = DateObj.getDate();
            var month = DateObj.getMonth() + 1;
            var fullYear = DateObj.getFullYear().toString();
            var setformattedDate = '';
            setformattedDate = getDigitToFormat(month) + '/' + getDigitToFormat(day)   + '/' + fullYear;
            return setformattedDate;
        }
        function getDigitToFormat(val) {

            if (val < 10) {
                val = '0' + val;
            }

            return val.toString();
        }

    </script>

Output :
How-to-add-days-to-date-in-jquery

Leave a Reply

Your email address will not be published. Required fields are marked *