Difference between two Dates in Years Months and Days in ASP.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

How Get c# difference between two dates in years months and days

Posted 2 months ago

Hi ahsan.ali,

Please take reference the below code and correct your code.

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    DateTime dtCurrent = DateTime.Now;
    DateTime dtDOB = new DateTime(2017, 05, 10);
    TimeSpan timeSpan = dtCurrent - dtDOB;
    DateTime age = DateTime.MinValue + timeSpan;
    int years = age.Year - 1;
    int months = age.Month - 1;
    int days = age.Day - 1;
    Response.Write(years.ToString() + " Year/s " + months.ToString() + " Month/s " + days.ToString() + " Day/s");
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim dtCurrent As DateTime = DateTime.Now
    Dim dtDOB As DateTime = New DateTime(2017, 5, 10)
    Dim timeSpan As TimeSpan = dtCurrent - dtDOB
    Dim age As DateTime = DateTime.MinValue + timeSpan
    Dim years As Integer = age.Year - 1
    Dim months As Integer = age.Month - 1
    Dim days As Integer = age.Day - 1
    Response.Write(years.ToString() & " Year/s " & months.ToString() & " Month/s " & days.ToString() & " Day/s")
End Sub

Output

1 Year/s 1 Month/s 1 Day/s