gpt4 book ai didi

vb.net - VB 2010 : How to calculate a date difference?

转载 作者:行者123 更新时间:2023-12-02 08:54:11 27 4
gpt4 key购买 nike

我想做一个程序,可以返回你的年龄,以年、月、周和日为单位。但我没有得到它来比较不同的时间。

输入是一个类似于 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

最佳答案

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

关于vb.net - VB 2010 : How to calculate a date difference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190694/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com