以年,月,日为单位的年龄计算 [英] Age calculation in years, months, days

查看:201
本文介绍了以年,月,日为单位的年龄计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码从特定数据库返回年龄.

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

这可能是防御性很强的代码(有很多重复的行,坏,坏,坏),但是它可以工作.我让你更漂亮.或询问代码审查"以获取更好的代码.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆