On 01/15/2017 07:58 AM, Nestor wrote:
I eventually came up with this, but it seems an ugly hack:
import std.stdio;
uint getAge(int yyyy, ubyte mm, ubyte dd) {
ubyte correction;
import std.datetime;
SysTime t = Clock.currTime();
if (t.month < mm) correction = 1;
else if (t.month == mm) correction = (t.day < dd) ? 1 : 0;
else correction = 0;
return (t.year - yyyy - correction);
}
void main() {
try
writefln("Edad: %s aƱos.", getAge(1958, 1, 21));
catch(Exception e) {
writefln("%s.\n(%s, line %s)", e.msg, e.file, e.line);
}
}
That's the better approach, I think. Years have variable lengths.
Determining "age" in years works by comparing dates, not durations.
I would write it like this, but as far as I see yours does the same thing:
----
int getAge(int yyyy, int mm, int dd)
{
import std.datetime;
immutable SysTime now = Clock.currTime();
immutable int years = now.year - yyyy;
return mm > now.month || mm == now.month && dd > now.day
? years - 1 // birthday hasn't come yet this year
: years; // birthday has already been this year
}
void main()
{
import std.stdio;
/* Day of writing: 2017-01-15 */
writeln(getAge(1980, 1, 1)); /* 37 */
writeln(getAge(1980, 1, 15)); /* 37 (birthday is today) */
writeln(getAge(1980, 1, 30)); /* 36 */
writeln(getAge(1980, 6, 1)); /* 36 */
}
----
Isn't there a built-in function to do this?
If there is, finding it in std.datetime would take me longer than
writing it myself.