Date>>ageOn: aDate
" assert: (self <= aDate)
| age |
age = aDate year - self year + 1.
aDate monthIndex < self monthIndex ifTrue: [ ^age - 1 ].
(aDate monthIndex = self monthIndex and: [aDate dayOfMonth < self
dayOfMonth]) ifTrue: [ ^age - 1 ].
^age
HTH .. Subbu
On Friday 21 July 2017 05:28 AM, Tim Mackinnon wrote:
Hi - I just ran a great MobProgramming session with Smalltalk for the XProLo
group - and there was lots of great feedback and questions, however one of them
really got me thinking…
We did a little exercise to create a Person class with name, dob - and then we
TDD’d an age method… which seems simple on the surface but it gets to an
interesting point - what about leap years? How old is someone on those years?
I thought that our plethora of Date/Duration classes might handle this - but I
couldn’t spot something obvious and was wondering if someone had a neat answer.
Essentially if you try:
age
^Date today - self dob
You get a Duration,
But there isn’t :
^(Date today - self dob) asYears
There is is asDay
^(Date today - self dob) asDays
But then can you really
^(Date today - self dob) asDays / 365) truncated
But what about leap years… so
^(Date today - self dob) asDays / 365.25) truncated
It all feels a bit inelegant and I suspect there is a better Smalltalk way that
is eluding me? Any suggestions?
Tim