Using Math.DivRem method to calculate year and months of experience in Asp.Net C#,VB

Introduction:  In this article I have explained how to get or compute years and months of experience from the months of experience value entered in textbox in Asp.Net with both C# and VB language.

Description: In one of my project I was storing employee’s experience in database in single INT column “MonthOfExperience”. But on Employee’s profile page I want to show Employee experience in the form like 2 year 7 months if the experience is of 31 months. So I need to calculate the number of years and months from the single months of experience value. I used the Math.DivRem method to get the desired result. Read more about Math.DivRem method.

Implementation: Let’s create a demo page for demonstration purpose.

HTML Source

<asp:TextBox ID="txtExperience" placeholder="Months of experience" runat="server" ></asp:TextBox>
<asp:Button ID="btnCalculate"  runat="server" Text="Calculate" OnClick="btnCalculate_Click" /><br />
<asp:Literal ID="ltrlExperince" runat="server"></asp:Literal>

Asp.Net C# Code

protected void btnCalculate_Click(object sender, EventArgs e)
{
ltrlExperince.Text = CalculateExperience(Convert.ToInt32(txtExperience.Text.Trim()));
}

public string CalculateExperience(Int32 monthsOfExperience)
{
int numberOfYears, numberOfMonths;
numberOfYears = Math.DivRem(monthsOfExperience, 12, out numberOfMonths);
return string.Format("{0} {1}", numberOfYears + " Year", numberOfMonths > 1 ? numberOfMonths + " Months" : numberOfMonths + " Month");
}

Asp.Net VB Code
Protected Sub btnCalculate_Click (sender As Object, e As EventArgs) Handles btnCalculate.Click
ltrlExperince.Text = CalculateExperience(Convert.ToInt32(txtExperience.Text.Trim()))
End Sub

Public Function CalculateExperience(monthsOfExperience As Int32) As String
Dim numberOfYears As Integer, numberOfMonths As Integer
numberOfYears = Math.DivRem(monthsOfExperience, 12, numberOfMonths)
Return String.Format("{0} {1}", numberOfYears + " Year", If(numberOfMonths > 1,    numberOfMonths + " Months", numberOfMonths + " Month"))
End Function

Now over to you:
Previous
Next Post »

Anonymous

very nice sir...

Anonymous

very nice sir...

Anonymous

very nice...