Calculate number of months between two dates using C# and VB.Net in ASP.Net

Last Reply 5 months ago By pandeyism

Posted 5 months ago

Hi friends,

How to convert days to total months in jquery?

Example: Mar-01-2019 to Apr-13-2019

need output as Example: (1.1 month)

Posted 5 months ago

Hi sureshMGR,

Refer below sample.

HTML

From :
<asp:TextBox runat="server" ID="txtFrom" Text="03/01/2019" />
<br />
To :
<asp:TextBox runat="server" ID="txtTo" Text="04/13/2019" />
<br />
<asp:Button Text="Submit" runat="server" ID="btnCalculate" OnClick="Calcalte" />

Code

C#

protected void Calcalte(object sender, EventArgs e)
{
    DateTime fromDate = Convert.ToDateTime(txtFrom.Text);
    DateTime toDate = Convert.ToDateTime(txtTo.Text);
    double month = Math.Round((toDate.Subtract(fromDate).TotalDays) / 30, 1);
    ScriptManager.RegisterStartupScript(this, this.GetType(), "CropImage", "alert('Total Months are : " + month + "');", true);
}

VB.Net

Protected Sub Calcalte(ByVal sender As Object, ByVal e As EventArgs)
    Dim fromDate As DateTime = Convert.ToDateTime(txtFrom.Text)
    Dim toDate As DateTime = Convert.ToDateTime(txtTo.Text)
    Dim month As Double = Math.Round((toDate.Subtract(fromDate).TotalDays) / 30, 1)
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "CropImage", "alert('Total Months are : " & month & "');", True)
End Sub

Screenshot