On Sunday, 15 January 2017 at 06:23:56 UTC, Dave Chapman wrote:
Does this do what you want?
import std.stdio;

uint getAge(int yyyy, int mm, int dd) {
  import std.datetime;
  SysTime t1 = SysTime(Date(yyyy, mm, dd));
  SysTime t2 = Clock.currTime();
  return( (t2.year - t1.year));
}

void main() {
  auto age = getAge(1980, 1, 1);
  writefln("age is %s", age);
}

It seems to work, but not very accurately, see variation:

import std.stdio;

uint getAge() {
  import std.datetime;
  SysTime t1 = SysTime(Date(2000, 12, 31));
  SysTime t2 = SysTime(Date(2001, 1, 1));
  return((t2.year - t1.year));
}

void main() {
  auto age = getAge();
  writefln("age is %s", age);
}


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);
  }
}

Isn't there a built-in function to do this?

Reply via email to