time difference - beautify my code

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 3 02:57:38 PDT 2015


On Thursday, July 02, 2015 19:03:48 dd0s via Digitalmars-d-learn wrote:
> i got a date t described in seconds from 1.1.1970, and i want to
> check if the current time is further than 12 hours from the given
> time t. the following code works but it's super ugly =S
>
> please give me some ideas how to make this code nicer :)
>
>    private static bool sessionIsCurrent(long t)
>    {
>      DateTime dateTime = DateTime(1970, 1, 1) +
> dur!"msecs"(t*1000);
>      DateTime curTime = DateTime() +
> dur!"hnsecs"(Clock.currStdTime());
>      return (curTime - dateTime) < dur!"msecs"(1000*60*60*12);
>    }
>
> thx for your effort

Well, as anonymous pointed out, you probably want something more like

return Clock.currTime() - SysTime(unixTimeToStdTime(t)) < hours(12);

And if you use DateTime the way you are in your current code, it'll treat
that time as if it were in local time, whereas unix time is in UTC. So,
you'd be off by the difference between UTC and your local time zone.

In addition, even if you want to use dur instead of the aliases, I would
point out that code like dur!"msecs"(t * 1000) doesn't make a lot of sense,
because you can just do dur!"seconds"(t) - or you can use the aliases (which
have the same names as the string template parameters) - e.g. seconds(t)
or hours(12). dur is required for generic code, but for non-generic code,
it's obviously up to you whether to use dur or the aliases, but most folks
prefer the aliases.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list