Access开发培训
网站公告
·Access专家课堂QQ群号:151711184    ·Access快速开发平台下载地址及教程    ·欢迎加入Access专家课堂微信群!    ·如何快速搜索本站文章|示例|资料    
您的位置: 首页 > 技术文章 > Access数据库-模块/函数/VBA

计算年龄

时 间:2007-11-15 09:44:13
作 者:ksiv   ID:11  城市:上海  QQ:3002789054点击这里给麥田发消息
摘 要:有一个人员花名册,有"出生年月"字段(格式yyyy-mm),如何计算出每个人的年龄,和全部人员的平均年龄.
正 文:

(Q) How do I calculate the age of a person given his/her birthdate?

(A) There are several methods to do this. I'll list two methods that have been posted to the newsgroups in the recent past:

Assuming that the birthdate field is called [BDate] and is of type date, you can use the following calculation

    Age=DateDiff("yyyy", [Bdate], Now())+ _
            Int( Format(now(), "mmdd") < Format( [Bdate], "mmdd") )

Alternate: You can use this function to calculate Age.

Function Age(Bdate, DateToday) As Integer
' Returns the Age in years between 2 dates
' Doesn't handle negative date ranges i.e. Bdate > DateToday

    If Month(DateToday) < Month(Bdate) Or (Month(DateToday) = _
                Month(Bdate) And Day(DateToday) < Day(Bdate)) Then
            Age = Year(DateToday) - Year(Bdate) - 1
    Else
            Age = Year(DateToday) - Year(Bdate)
    End If
End Function

    Here's another detailed Age Checker.

'--- CODE START ---
Public Sub CalcAge(vDate1 As Date, vdate2 As Date, ByRef vYears As Integer,
ByRef vMonths As Integer, ByRef vDays As Integer)
    ' Comments  : calculates the age in Years, Months and Days
    ' Parameters:
    '    vDate1 - D.O.B.
    '    vDate2 - Date to calculate age based on
    '    vYears - will hold the Years difference
    '    vMonths - will hold the Months difference
    '    vDays - will hold the Days difference
    vMonths = DateDiff("m", vDate1, vdate2)
    vDays = DateDiff("d", DateAdd("m", vMonths, vDate1), vdate2)
    If vDays < 0 Then
        ' wierd way that DateDiff works, fix it here
        vMonths = vMonths - 1
        vDays = DateDiff("d", DateAdd("m", vMonths, vDate1), vdate2)
    End If
    vYears = vMonths \ 12 ' integer division
    vMonths = vMonths Mod 12 ' only want leftover less than one year
End Sub
'--- CODE END ---


Access软件网QQ交流群 (群号:54525238)       Access源码网店

常见问答:

技术分类:

相关资源:

专栏作家

关于我们 | 服务条款 | 在线投稿 | 友情链接 | 网站统计 | 网站帮助