以年、月、日为单位的年龄计算 [英] Age calculation in years, months, days
问题描述
以下代码从特定数据库返回年龄.
The following code returns the age from a particular database.
我要添加什么才能获得以年、月、日为单位的确切日期?
What do I add to get the exact date in years, months, days?
<%= DateDiff("yyyy",rs("Dateofbirth"),date)%>
即结果应该是 12 岁 6 个月零 8 天.
i.e. result should be 12 yrs 6 months 8 days old.
推荐答案
DateDiff("d",rs("Dateofbirth"),date) 会给你一些天数.DateDiff("m",rs("Dateofbirth"),date) 会给你几个月的时间.
DateDiff("d",rs("Dateofbirth"),date) will give you a number of days. DateDiff("m",rs("Dateofbirth"),date) will give you a number of months.
所以,类似于(我不知道什么是 rs()):
So, something like(I don't know exactly what is rs()) :
CurrentDate = rs("Dateofbirth")
Years = DateDiff("yyyy", CurrentDate ,date)
ThisYear = DateAdd("yyyy", Years, CurrentDate)
Months = DateDiff("m", ThisYear ,date)
ThisMonth = DateAdd("m", Months, CurrentDate)
Days = DateDiff("d", ThisMonth, date)
Age = CStr(Years) & " years" & CStr(Months) & " months" & CStr(Days) & Days
但经过一些玩弄后,它并不总是有效.差异有些四舍五入.所以在某些情况下,我有几天或几个月的负数.所以我发疯并过度保护代码:
But after some toying, it didn't always work. The difference is somewhat rounded up. So I had negative numbers for days or months, in some occurences. So I went mad and overprotected the code :
MsgBox(Age("09-12-1946"))
Function Age(DateOfBirth)
Dim CurrentDate, Years, ThisYear, Months, ThisMonth, Days
CurrentDate = CDate(DateOfBirth)
Years = DateDiff("yyyy", CurrentDate, Date)
ThisYear = DateAdd("yyyy", Years, CurrentDate)
Months = DateDiff("m", ThisYear, Date)
ThisMonth = DateAdd("m", Months, ThisYear)
Days = DateDiff("d", ThisMonth, Date)
Do While (Days < 0) Or (Months < 0)
If Days < 0 Then
Months = Months - 1
ThisMonth = DateAdd("m", Months, ThisYear)
Days = DateDiff("d", ThisMonth, Date)
End If
If Months < 0 Then
Years = Years - 1
ThisYear = DateAdd("yyyy", Years, CurrentDate)
Months = DateDiff("m", ThisYear, Date)
ThisMonth = DateAdd("m", Months, ThisYear)
Days = DateDiff("d", ThisMonth, Date)
End If
Loop
Age = Years & "y/" & Months & "m/" & Days
End Function
这可能是过度防御性的代码(有很多重复的行,糟糕的糟糕的),但它有效.我离开你让它更漂亮.或者在 Code Review 上询问更好的代码.
It's probably excessively defensive code(with many repeated lines, bad bad bad), but it works. I leave you making it prettier. Or ask on Code Review for a nicer code.
这篇关于以年、月、日为单位的年龄计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!