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 asp.net.
- 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 .
Click on image to enlarge |
In previous articles i explained How to Convert Rupees,Currency or Numbers to Words in Asp.net C# and How to Fill Country,State,Cities in the DropDownList in asp.net C#,VB.Net and How to create and consume WCF Services in asp.net ? and Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and WCF Service to bind,insert,edit,update,delete from sql server database in asp.net and How to create crystal reports in visual studio 2010 using asp.net .
Implememetation: Now let's create an asp.net website to understand. Place a ScriptManager control, two TextBox and Button control from the Visual studio toolkit.
Implememetation: Now let's create an asp.net website to understand. Place a ScriptManager control, two TextBox and Button control from the Visual studio toolkit.
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 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>
- 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 asp.net
- 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;
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{}
}
VB.Net Code to get age in years,months,days,hours and seconds from DOB in asp.net
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
Next
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
Try
Dim dtVal As
String = txtDOB.Text.Trim()
Dim Dob As
DateTime = Convert.ToDateTime(dtVal)
txtCalculatedAge.Text = CalculateAge(Dob)
Catch
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."
6 comments
Click here for commentsi got error like,
ReplySystem.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
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..
ReplyHello Sir,
Replyi 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.
Hi,i wanna see HOW TO PRINT RECORDS FROM GRIDVIEW inasp.net.Thank you very much...
Replythank u very much.easy code
Replyyour welcome..i am glad you found this article useful...
ReplyIf 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..