Get age in years,months,days,hours and seconds from DOB in C#,Vb.Net

Introduction : Through this article you will learn the following:
  • How to get/calculate age in years, months, days, hours and seconds from Date of Birth or we can say any date in
  • How to validate date using RegularExpression validation control.
  • How to implement Ajax CalendarExtendar control for selecting DOB or Date.
  • How to set the Start date and End Date in the Ajax CalendarExtendar control .

Get age in years,months,days,hours and seconds from DOB in
Click on image to enlarge
Also place CalendarExtendar control from the AjaxControlToolKit if you have already installed the AjaxControlToolkit.

If not then you can follow the instructions to install the AjaxControlToolkit from my previous article.
  • In the design page (.aspx) design the page as:
<fieldset  style="width:440px;">
    <legend>Get age in years,months,days,hours and seconds from DOB in</legend>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
    <td>DOB: </td><td>
        <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>
        <asp:CalendarExtender ID="CalendarExtender1"
        <asp:Button ID="btnGetAge" runat="server" Text="Get Age"
            onclick="btnGetAge_Click" />
        <asp:RequiredFieldValidator ID="rfvDOB" runat="server"
            ErrorMessage="Please select Date of Birth" ControlToValidate="txtDOB"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="rgeDob" runat="server"
            ControlToValidate="txtDOB" ErrorMessage="Please enter dob in dd/mm/yyyy format"
            Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
        <asp:TextBox ID="txtCalculatedAge" runat="server" TextMode="MultiLine"
            Height="39px" Width="353px" Rows="3"></asp:TextBox>

  • Have you noticed the line <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> added automatically next to the very first line in the design page. Actually it registers the Ajax Control on placing CalendarExtendar control on design page.

C#.Net Code to get age years,months,days,hours and seconds from DOB in 
  • In the code behind file (.aspx.cs) write the code as:
protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            CalendarExtender1.EndDate = System.DateTime.Now;

    private string CalculateAge(DateTime Dob)
        DateTime Now = DateTime.Now;
        int Years = new DateTime(DateTime.Now.Subtract(Dob).Ticks).Year - 1;
        DateTime PastYearDate = Dob.AddYears(Years);
        int Months = 0;
        for (int i = 1; i <= 12; i++)
            if (PastYearDate.AddMonths(i) == Now)
                Months = i;
            else if (PastYearDate.AddMonths(i) >= Now)
                Months = i - 1;
        int Days = Now.Subtract(PastYearDate.AddMonths(Months)).Days;
        int Hours = Now.Subtract(PastYearDate).Hours;
        int Minutes = Now.Subtract(PastYearDate).Minutes;
        int Seconds = Now.Subtract(PastYearDate).Seconds;
        return String.Format("Age: {0} Year(s) {1} Month(s) {2} Day(s) {3} Hour(s) {4} Second(s)",
                            Years, Months, Days, Hours, Seconds);
    protected void btnGetAge_Click(object sender, EventArgs e)
            string dtVal = txtDOB.Text.Trim();
            DateTime Dob = Convert.ToDateTime(dtVal);
            txtCalculatedAge.Text = CalculateAge(Dob);

VB.Net Code to get age in years,months,days,hours and seconds from DOB in
Design the page same as in the above C# secion and Just replace the line <asp:Button ID="btnGetAge" runat="server" Text="Get Age" onclick="btnGetAge_Click" /> with <asp:Button ID="btnGetAge" runat="server" Text="Get Age"/>
  • In the code behind file (.aspx.vb) write the code as:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            CalendarExtender1.EndDate = System.DateTime.Now
        End If
    End Sub

    Private Function CalculateAge(Dob As DateTime) As String
        Dim Now As DateTime = DateTime.Now
        Dim Years As Integer = New DateTime(DateTime.Now.Subtract(Dob).Ticks).Year - 1
        Dim PastYearDate As DateTime = Dob.AddYears(Years)
        Dim Months As Integer = 0
        For i As Integer = 1 To 12
            If PastYearDate.AddMonths(i) = Now Then
                Months = i
                Exit For
            ElseIf PastYearDate.AddMonths(i) >= Now Then
                Months = i - 1
                Exit For
            End If
        Dim Days As Integer = Now.Subtract(PastYearDate.AddMonths(Months)).Days
        Dim Hours As Integer = Now.Subtract(PastYearDate).Hours
        Dim Minutes As Integer = Now.Subtract(PastYearDate).Minutes
        Dim Seconds As Integer = Now.Subtract(PastYearDate).Seconds
        Return [String].Format("Age: {0} Year(s) {1} Month(s) {2} Day(s) {3} Hour(s) {4} Second(s)", Years, Months, Days, Hours, Seconds)
    End Function

    Protected Sub btnGetAge_Click(sender As Object, e As System.EventArgs) Handles btnGetAge.Click
            Dim dtVal As String = txtDOB.Text.Trim()
            Dim Dob As DateTime = Convert.ToDateTime(dtVal)
            txtCalculatedAge.Text = CalculateAge(Dob)
        End Try
    End Sub

Now over to you:

"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Next Post »


Click here for comments
September 23, 2013 ×

i got error like,

System.Web.UI.WebControls.Calendar' does not contain a definition for 'EndDate' and no extension method 'EndDate' accepting a first argument of type 'System.Web.UI.WebControls.Calendar' could be found (are you missing a using directive or an assembly reference?)

and i didn't set System.Web.UI.WebControls.Calendar...
thank you

September 23, 2013 ×

Hello Siva..Have you properly installed the ajax control toolkit? this article is completely working..i suggest you to read the article thoroughly and recheck your code again..if still you face problem then let me know.i will help you to sort out the problem..

March 20, 2014 ×

Hello Sir,
i m making a project on custom jewellery designing web application. where a user should be able to drag and drop gems,stones,chain types and design their own customised jewelry. how to start it.not getting any idea.

April 11, 2014 ×

Hi,i wanna see HOW TO PRINT RECORDS FROM GRIDVIEW you very much...

December 10, 2014 ×

thank u very much.easy code

December 11, 2014 ×

your welcome..i am glad you found this article useful...


If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..