[squeak-dev] Chronology and birthdays/ages
David T. Lewis
lewis at mail.msen.com
Sat Jun 26 16:59:29 UTC 2021
On Sat, Jun 26, 2021 at 01:13:06PM +0200, Bal??zs K??si wrote:
> Ken's solution can be fixed for non-leap years by using <= instead of <,
> but it breaks down for leap years. e.g.
>
> a := Date year: 2003 month: 3 day: 1.
> b := Date year: 2004 month: 2 day: 29.
>
> b year - a year - (a dayOfYear <= b dayOfYear ifTrue: 0 ifFalse: 1) "
> outputs 1 "
>
> What seems to work is to let Date handle the leap year case with
> #addMonths:. e.g.
>
> yd := b year - a year.
> (a addMonths: 12 * yd) > b ifTrue: [ yd - 1 ] ifFalse: [ yd ]. " outputs 0 "
> Bal??zs
>
Here is another variation that seems to work with leap years:
Date ageAt: aDate
"Given a date representing a person's birthday, answer that person's age at
aDate as reported in the Western tradition. Note that age is reported differently
in India and possibly other cultures."
" '9 Aug 1984' asDate ageAt: Date today "
^ (aDate monthIndex > self monthIndex
or: [aDate monthIndex = self monthIndex and: [aDate dayOfMonth >= self dayOfMonth]])
ifTrue: [aDate year - self year]
ifFalse: [aDate year - self year - 1].
It's a bit discouraging when I use this with my real birthday though ;-)
Dave
More information about the Squeak-dev
mailing list
|