VB 2010:如何计算日期差异?

时间:2011-05-31 16:34:49

标签: vb.net

我想制作一个程序,让你知道你的年龄,年,月,周和日。但我没有比较不同的时间。

输入是一个看起来像01.01.2011(dd.mm.yyyy)的字符串。

拜托,有人可以帮忙吗?

非常感谢!

编辑:

到目前为止,我的代码是:

Try
        dim date1 as string = '01.01.2011'
        ' Today
        Dim date2 As Date
        date2 = Date.Now
        ' number of seconds since date1
        Dim seconds As Long
        seconds = DateDiff("s", date1, date2)
        lbl_seconds.Text = seconds.ToString & " Seconds"
        ' Number of minutes since date1
        Dim Minutes As Long
        Minutes = DateDiff("n", date1, date2)
        lbl_minutes.Text = Minutes.ToString & " Minutes"
        ' Number of hours since date1
        Dim hours As Long
        hours = DateDiff("h", date1, date2)
        lbl_hours.Text = hours.ToString & " Hours"
        ' Days
        Dim days As Long
        days = DateDiff("d", date1, date2)
        lbl_days.Text = days.ToString & " Days"
        ' weeks
        Dim weeks As Long
        weeks = DateDiff("ww", date1, date2)
        lbl_weeks.Text = weeks.ToString & " Weeks"
        'months
        Dim months As Long
        months = DateDiff("m", date1, date2)
        lbl_months.Text = months.ToString & " Months"
        ' Years
        Dim years As Long
        years = DateDiff("yyyy", date1, date2)
        lbl_years.Text = years.ToString & " Years"


    Catch ex As Exception
        date1 = "01.01.2011"
        MsgBox("not a valid date given!")
    End Try

1 个答案:

答案 0 :(得分:6)

DateDiff是一个VB函数,不是标准.Net库的一部分(所以C#不能使用它)。

使用TimeSpan课程和toString() method with Custom TimeSpan Format String可以更轻松地获得您想要的内容。

修改

以下是代码,您可以将结果与http://www.easycalculation.com/date-day/age-calculator.php进行比较:

Dim birthday As New DateTime(1990, 1, 1)
Dim ts As TimeSpan = DateTime.Now.Subtract(birthday)

Dim years As Integer, months As Integer, days As Integer, hours As Integer, minutes As Integer, seconds As Integer

' compute difference in total months
months = 12 * (DateTime.Now.Year - birthday.Year) + (DateTime.Now.Month - birthday.Month)

' based upon the 'days',
' adjust months & compute actual days difference
If DateTime.Now.Day < birthday.Day Then
    months -= 1
    days = DateTime.DaysInMonth(birthday.Year, birthday.Month) - birthday.Day + DateTime.Now.Day
Else
    days = DateTime.Now.Day - birthday.Day
End If
' compute years & actual months
years = Math.Floor(months / 12)
months -= years * 12

hours = ts.Hours
minutes = ts.Minutes
seconds = ts.Seconds