Contoh program untuk menghitung umur dengan Visual Basic 6.
1. Fungsi calculateAge adalah fungsi untuk menghitung umur yang akan mengembalikan nilai string yang berisi informasi x Tahun, x Bulan dan x Hari
2. Sub test adalah contoh untuk memanggil fungsi calculateAge
Function calculateAge(dateOfBird As Date, fromData As Date) As String
Dim dateNow As Date
Dim tgl As Date
Dim tgl1 As Date
Dim years As Long
Dim months As Long
Dim days As Long
Dim yearWord As String
Dim monthWord As String
Dim dayWord As String
dateNow = fromData
tgl = dateOfBird
' menghitung tahun
years = DateDiff("yyyy", tgl, dateNow)
If month(tgl) > month(dateNow) Then
years = years - 1
ElseIf month(tgl) = month(dateNow) And day(tgl) > day(dateNow) Then
years = years - 1
ElseIf month(tgl) = month(dateNow) And day(tgl) = day(dateNow) Then
GoTo finally ' jika bulan dan tanggal sama maka perhitungan selesai
End If
' menghitung bulan
tgl = DateAdd("yyyy", years, tgl)
months = DateDiff("m", tgl, dateNow)
If day(tgl) > day(dateNow) Then
months = months - 1
ElseIf month(tgl) = month(dateNow) And day(tgl) >= day(dateNow) Then
months = months - 1
End If
tgl = DateAdd("m", months, tgl)
' menghitung hari
days = DateDiff("d", tgl, dateNow)
finally:
yearWord = IIf(years = 0, "", years & " Tahun ")
monthWord = IIf(months = 0, "", months & " Bulan ")
dayWord = IIf(days = 0, "", days & " Hari ")
calculateAge = yearWord & monthWord & dayWord
calculateAge = Trim(calculateAge)
End Function
Private Sub test()
Dim strMsg As String
strMsg = "Umur : " & calculateAge(#1/30/2000#, #6/26/2008#)
'result = "Umur : 8 Tahun 4 Bulan 27 Hari"
MsgBox strMsg, vbInformation
End Sub
Filed under: VB 6