Wednesday, February 27, 2013

Calculate Age from Date of Birth Using Java Script

In my previous posts, I explained jQuey .toggleClass() Example in ASp.Net, jQuery Draggable Div Example in ASP.Net, Disable cut, copy and paste in textbox using jquery, javascript, Watermark in textbox using JavaScript and many other articles related to jQuery and Java Script.

Here, I am going to explain how to calculate the age of person from data of birth using Java Script. In some cases we need to calculate the age of person . We can calculate the age using Java Script on client side very easily.
To implement the code for calculating age of personn using Java Script , you have to write the following code-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JavaScriptAgeCalculation._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Calculate Age using Java Script</title>
    <script type="text/javascript">
        function CalculateAge() {       
            var inputdob = document.getElementById("txtDOB").value;
            //regular expression to validate date formate mm/dd/yyyy
            var rex = /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/;
            if (rex.test(inputdob)) {
                //convet to input date into Date object
                var DOBDate = new Date(inputdob);
                //get the current date
                var currentDate = new Date();
                var monthDiff = currentDate.getMonth() - DOBDate.getMonth();
                var yearDiff = currentDate.getFullYear() - DOBDate.getFullYear();
                var dayDiff = currentDate.getDate() - DOBDate.getDate();
                if (isNaN(yearDiff)) {
                    document.getElementById("lblAgeMesg").innerHTML = "Input date is incorrect.";
                }
                else {               
                    if (monthDiff < 0 ) {
                        yearDiff = parseInt(yearDiff,10) - 1;
                        monthDiff= 12 + parseInt(monthDiff,10);
                        if(dayDiff < 0){
                          monthDiff = parseInt(monthDiff,10)-1;
                          dayDiff = 30 + parseInt(dayDiff,10);
                          document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                        }
                        else{
                          document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                        }
                    }
                    else {
                        if(monthDiff==0){
                            yearDiff = parseInt(yearDiff,10) - 1;
                            if(dayDiff < 0){                             
                              dayDiff = 30 + parseInt(dayDiff,10);
                              document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                            }
                            else{
                              document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                            }
                        }
                        else{
                            if(dayDiff < 0){
                                  monthDiff = parseInt(monthDiff,10)-1;
                                  dayDiff = 30 + parseInt(dayDiff,10);
                                  document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                                }
                                else{
                                  document.getElementById('lblAgeMesg').innerHTML = 'Age : ' + yearDiff + ' Years ' + monthDiff + ' Months ' + dayDiff + ' Days';
                                }
                        }
                    }
                }
            }
            else {
                document.getElementById('lblAgeMesg').innerHTML = 'Date must be of mm/dd/yyyy format';
            }          
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:Label ID="lblDOB" runat="server" Text="Enter Your Date of Birth : "></asp:Label>
                <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox><label>(mm/dd/yyyy)</label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnAge" runat="server" Text="Calculate Age" OnClientClick="CalculateAge(); return false;" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblAgeMesg" runat="server"></asp:Label>               
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

In the above code, I have used the regular expression to validate the input date format. Here I am using mm/dd/yyyy format.

Regular Expresion- /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/

 

Live Demo


To see the live demo, enter the date of birth in textbox below and click on the "Calculate Age" button.


4 comments:

  1. very useful post thank you to share it.

    ReplyDelete
  2. I do not even understand how I finished up right here,
    but I thought this post was great. I don't recognize
    who you are however definitely you are going to a famous
    blogger should you aren't already. Cheers!

    My web-site :: make money online

    ReplyDelete

^ Scroll to Top