joomla visitors
Mithila Software Blog | Calculating age in years and months in asp.net c#

Calculating age in years and months in asp.net c#

January 08, 2013 Posted by Mithila Software

There may be many occasions when you need to output the current age of a user in your database with respect to the current date and time especially in profile of user in content management system or for any other purpose.You can use the c# method below to carry out this error prone task with accuracy and ease. Take a look at how this works.

This is the method -

public string agecalculate(string date)
   {
       DateTime today = DateTime.Today;
       DateTime bdate = Convert.ToDateTime(date); 
 
       System.Collections.ArrayList arr = new System.Collections.ArrayList();
       arr = span(today, bdate); 
 
       return arr[0].ToString() + " years " + arr[1].ToString() + " months"; 
 
   }
   public string ageyears(string date)
   {
       DateTime today = DateTime.Today;
       DateTime bdate = Convert.ToDateTime(date); 
 
       System.Collections.ArrayList arr = new System.Collections.ArrayList();
       arr = span(today, bdate); 
 
       return arr[0].ToString(); 
 
   } 
 
   public System.Collections.ArrayList span(DateTime f, DateTime l)
   {
       int days;
       int months;
       int years; 
 
       int fird = f.Day;
       int lasd = l.Day; 
 
       int firm = f.Month;
       int lasm = l.Month; 
 
       if (fird >= lasd)
       {
           days = fird - lasd;
           if (firm >= lasm)
           {
               months = firm - lasm;
               years = f.Year - l.Year;
           }
           else
           {
               months = (firm + 12) - lasm;
               years = f.AddYears(-1).Year - l.Year;
           }
       }
       else
       {
           days = (fird + 30) - lasd;
           if ((firm - 1) >= lasm)
           {
               months = (firm - 1) - lasm;
               years = f.Year - l.Year;
           }
           else
           {
               months = (firm - 1 + 12) - lasm;
               years = f.AddYears(-1).Year - l.Year;
           }
       } 
 
       if (days < 0)
       {
           days = 0 - days;
       }
       if (months < 0)
       {
           months = 0 - months;
       }
       System.Collections.ArrayList ar = new System.Collections.ArrayList();
       ar.Add(years.ToString());
       ar.Add(months.ToString());
       ar.Add(days.ToString());
       return ar;
   }

 

How to call this method -

Response.Write(agecalculate("10/10/1986"));

 

Easy ! Isn’t it ?

Tags:

Asp.Net

blog comments powered by Disqus
Address ::
Mithila Software Solutions,
Green House , 3 GM Road ,
Near Radio Station , Darbhanga
PIN:: 846004
Phone :: # 099-397-49350