On 15/01/2017 4:43 PM, Nestor 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.

So I had a go at this and found I struggled looking at "magic" functions and methods.
Turns out there is a much simpler answer.

int getAge(int yyyy, int mm, int dd) {
  import std.datetime;
  auto t1 = cast(DateTime)SysTime(Date(yyyy, mm, dd));
  auto t2 = cast(DateTime)Clock.currTime();

  int numYears;
  while(t2 > t1) {
     t1.add!"years"(1);
     numYears++;
  }

  return numYears;
}

Reply via email to