Convert duration to years?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 15 12:02:12 PST 2017


On Sunday, January 15, 2017 03:43:32 Nestor via Digitalmars-d-learn wrote:
> Hi,
>
> I would simply like to get someone's age, but I am a little lost
> with time and date functions. I can already get the duration, but
> after reading the documentation it's unclear to me how to convert
> that into years. See following code:
>
> import std.stdio;
>
> void getAge(int yyyy, int mm, int dd) {
>    import std.datetime;
>    SysTime t1 = SysTime(Date(yyyy, mm, dd));
>    SysTime t2 = Clock.currTime();
>    writeln(t2 - t1);
> }
>
> int main() {
>    try
>      getAge(1980, 1, 1);
>    catch(Exception e) {
>      writefln("%s.\n(%s, line %s)", e.msg, e.file, e.line);
>    }
> }
>
> Notice getAge should return ubyte instead of void, only I haven't
> been able to find how to do it. Any suggestion would be welcome.
>
> Thanks in advance.

Well, there's diffMonths:

http://dlang.org/phobos/std_datetime.html#.SysTime.diffMonths

However, I doubt that it really does quite what you want. Because of the
varying lengths of months and years, you're probably going to have to write
code that does what you want with some combination of function. You probably
want to do something like

void getAge(int yyyy, int mm, int dd)
{
    auto birthdate = Date(yyyy, mm, dd);
    auto currDate = cast(Date)Clock.currTime;
    // This make Feb 29th become March 1st
    auto birthdayThisYear = Date(currDate.year, mm, 1) + days(dd - 1);
    auto years = currDate.year - birthdate.year;
    if(currDate < birthdayThisYear)
        --years;
    writeln(years);
}

I _think_ that that does it, but I'd want to do something like

void printAge(int yyyy, int mm, int dd)
{
    writeln(getAge(cast(Date)Clock.currTime(), yyyy, mm, dd);
}

int getAge(Date currDate, int yyyy, int mm, int dd)
{
    auto birthdate = Date(yyyy, mm, dd);
    auto currDate = cast(Date)Clock.currTime;
    // This make Feb 29th become March 1st
    auto birthdayThisYear = Date(currDate.year, mm, 1) + days(dd - 1);
    auto years = currDate.year - birthdate.year;
    if(currDate < birthdayThisYear)
        --years;
    return years;
}

and then add unit tests for getAge to verify that it did the correct thing
for various dates. It's quite possible that there's something subtley wrong
with it. Also, depending on what exactly you're trying to do, it's possible
that I didn't quite understand what you're trying to do and that it needs
some additional tweaks in order to do what you want.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list