Saturday, 17 January 2015

How to compare two dates in ASP.NET using JAVASCRIPT

In this article, i am going to show how to validate two dates in asp.net using JavaScript. It also make sure that difference between two dates should not be more than n number of days. In my case, i specified 7 but you can specify it according to your need.

function ValidateDate() {
                var startDate = document.getElementById("<%=txtDatefrom.ClientID%>");
                var endDate = document.getElementById("<%=txtDateTo.ClientID%>");
                //Get 1 day in milliseconds
                var oneDay = 1000 * 60 * 60 * 24;
                
                // to make sure end date is greater than or equal to start date
                if ((Date.parse(startDate.value) > Date.parse(endDate.value))) {
                    $(endDate).css('border', '1px solid red');
                    return false;
                }

                else {
                    // to make sure difference between two dates should not be more than 7 days
                    if (Math.round((Date.parse(endDate.value) - Date.parse(startDate.value)) / oneDay) > 7) {
                        $(endDate).css('border', '1px solid red');
                        return false;
                    }
                    $(endDate).css('border', '1px solid #d3cfc7');
                    return true;
                }
            }

No comments:

Post a Comment