如何计算asp.net vb中文本框中两个日期之间的差异

时间:2014-05-31 00:10:01

标签: asp.net

我需要在文本框中找到两个日期之间的差异。差异应该是年,月和日期。 我尝试使用Datediff,但它不适用于几个月和几天

Dim y_diff As Integer
    Dim m_diff As Integer
    Dim d_diff As Integer
    Dim date1 As Date = Convert.ToDateTime(Textbox1.Text)
    Dim dob As Date = Convert.ToDateTime(TextBox2.Text)
    Response.Write("Today date is " & Today.Date & "<br>")
    y_diff = DateDiff("yyyy", dob, date1)

    m_diff = DateDiff("m", dob, date1) / y_diff / 12

    d_diff = DateDiff("d", dob, date1) / 365
    Response.Write("Difference in year" & y_diff & "<br>" & "months" & m_diff & "<br>" & d_diff & "<br>")

我怎样才能正确使用它?

1 个答案:

答案 0 :(得分:0)

尝试使用此

TimeSpan diff = date1.Subtract(dob);
long Years = Convert.ToInt64(diff.TotalDays) / 365;
long Months = (Convert.ToInt64(diff.TotalDays) - (Years * 365)) / 30;
long Days = Convert.ToInt64(diff.TotalDays) - ((Years * 365) + (Months * 30)); 
int totaldays = diff.Days + 1;

这对你来说很完美。如果得到帮助,请告诉我。