首页 /编程语言和算法/VB6/VBA/ASP
 TB 输入生日并计算精确年龄的代码
今天 00:46

TWinBaisc 输入生日并计算精确年龄的代码:

[Description("")]
[FormDesignerId("D68C6AE0-3819-4BCA-8BE0-EC91B17DF596")]
[PredeclaredId]
Class Form1

    Private Sub Command1_Click()
        Call s_CalculateAge
    End Sub
    
    Private Sub s_CalculateAge()
        Dim birthDate As Date
        Dim currentDate As Date
        Dim ageYears As Integer
        Dim ageMonths As Integer
        Dim ageDays As Integer
        Dim inputStr As String
    
        ' 获取当前日期
        currentDate = Date
    
        ' 提示用户输入生日
        inputStr = InputBox("请输入你的生日(格式:YYYY-MM-DD):")
        If IsDate(inputStr) Then
            birthDate = CDate(inputStr)
        Else
            MsgBox "输入的日期格式不正确,请使用 YYYY-MM-DD 格式。"
            Exit Sub
        End If
    
        ' 计算年龄
        ageYears = Year(currentDate) - Year(birthDate)
        If Month(currentDate) < Month(birthDate) Or (Month(currentDate) = Month(birthDate) And Day(currentDate) < Day(birthDate)) Then
            ageYears = ageYears - 1
        End If
    
        ageMonths = Month(currentDate) - Month(birthDate)
        If Day(currentDate) < Day(birthDate) Then
            ageMonths = ageMonths - 1
        End If
        If ageMonths < 0 Then
            ageMonths = ageMonths + 12
        End If
    
        ageDays = Day(currentDate) - Day(birthDate)
        If ageDays < 0 Then
            Dim prevMonthLastDay As Integer
            prevMonthLastDay = Day(DateSerial(Year(currentDate), Month(currentDate), 0))
            ageDays = ageDays + prevMonthLastDay
        End If
    
        ' 显示结果
        MsgBox "你的精确年龄是:" & ageYears & " 岁 " & ageMonths & " 个月 " & ageDays & " 天。"
    End Sub
    
End Class

输入:

2000-1-1

运行结果:

你的精确年龄是:25 岁 3 个月 25 天。


 
全部回复(0)
首页 | 电脑版 |