|
-
Jun 30th, 2005, 05:49 AM
#1
Thread Starter
Addicted Member
Calculating Months
Hi All,
I need to be able to calculate the age of a person in both years and months. The years I have sorted but the code for working out the number of months does not. It appears to work for the first 5 months but after that it goes weird.
VB Code:
'get the age in months
Dim date1 As Date
Dim date2 As Date
Dim mnths As Integer
Dim yrs As Integer
Dim mnthcalc As Integer
'set date to today
date1 = Now
date2 = dtDOB.Value
mnths = DateDiff(DateInterval.Month, date2, date1)
yrs = DateDiff(DateInterval.Year, date2, date1)
If yrs = 0 Then
txtMonths.Text = mnths
Else
'mnthcalc = yrs * 12
'txtMonths.Text = (mnths - mnthcalc)
mnthcalc = mnths / 12
txtMonths.Text = mnthcalc
End If
any help appreciated.
-
Jun 30th, 2005, 06:21 AM
#2
Re: Calculating Months
I'd suggest that you use the DateTime and TimeSpan structures to do this calculation rather than using the old DateDiff function. Haven't time to implement right now but I'll be back within a few hours.
-
Jun 30th, 2005, 06:57 AM
#3
Thread Starter
Addicted Member
Re: Calculating Months
Cheers,
I haven't used those before, an example would be greatly appreciated.
Cheers
-
Jun 30th, 2005, 10:08 AM
#4
Re: Calculating Months
Actually, you lie. You have used the DateTime structure before because the in-built Date data type is actually implemented using the DateTime structure. Every Date object is a DateTime structure. We'll forget the TimeSpan for now as it's not needed for this example. Assuming that the person's date of birth is stored in a Date variable called dtDOB, you would get their current age in whole months like this:
VB Code:
Dim ageInMonths As Integer = (Date.Now.Year - dtDOB.Year) * 12 + (Date.Now.Month - dtDOB.Month)
If Date.Now.Day < dtDOB.Day Then
'The current month is yet to be completed.
ageInMonths -= 1
End If
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|