Friday, August 1, 2014

Get age in years,months,days,hours and seconds from DOB in asp.net

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 440px;">
            <legend>Get age in years,months,days,hours and seconds from DOB in asp.net</legend>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <table>
                <tr>
                    <td>
                        DOB:
                    </td>
                    <td>
                        <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>
                        <asp:CalendarExtender ID="CalendarExtender1" PopupButtonID="txtDOB" PopupPosition="Right"
                            TargetControlID="txtDOB" Format="dd/MM/yyyy" StartDate="01/01/1900" runat="server">
                        </asp:CalendarExtender>
                        <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" SetFocusOnError="True" ValidationExpression="^(((0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)/(0[13456789]|1[012])/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])/02/((19|[2-9]\d)\d{2}))|(29/02/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"
                            Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:TextBox ID="txtCalculatedAge" runat="server" TextMode="MultiLine" Height="39px"
                            Width="353px" Rows="3"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
    </form>
</body>
</html>
 =====================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    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;
                break;
            }
            else if (PastYearDate.AddMonths(i) >= Now)
            {
                Months = i - 1;
                break;
            }
        }
        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)
    {
        try
        {
            string dtVal = txtDOB.Text.Trim();
            DateTime Dob = Convert.ToDateTime(dtVal);
            txtCalculatedAge.Text = CalculateAge(Dob);
        }
        catch { }
    }
}