time difference - beautify my code
    anonymous via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Thu Jul  2 12:42:57 PDT 2015
    
    
  
On Thursday, 2 July 2015 at 19:03:49 UTC, dd0s wrote:
> i got a date t described in seconds from 1.1.1970,
I.e., you have a unix timestamp.
> 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);
dur!"msecs"(t*1000) -> dur!"seconds(t) -> t.seconds
Better yet (`to` from std.conv):
auto dateTime = SysTime(unixTimeToStdTime(t)).to!DateTime;
Or just go with SysTime instead of DateTime:
auto dateTime = SysTime(unixTimeToStdTime(t));
>     DateTime curTime = DateTime() + 
> dur!"hnsecs"(Clock.currStdTime());
Like above, use `to` to convert from SysTime to DateTime:
auto curTime = Clock.currTime.to!DateTime;
or just use a SysTime:
SysTime curTime = Clock.currTime;
>     return (curTime - dateTime) < dur!"msecs"(1000*60*60*12);
Like above, dur!"msecs"(1000*60*60*12) -> dur!"seconds"(60*60*12) 
-> dur!"minutes"(60*12) -> dur!"hours"(12) -> 12.hours
>   }
Putting it all together, removing the now pointless variable 
curTime, adding a pinch of immutable for the taste:
private static bool sessionIsCurrent(long t)
{
     immutable dateTime = SysTime(unixTimeToStdTime(t));
     return (Clock.currTime - dateTime) < 12.hours;
}
Final thoughts:
You may want to check that t is not in the future.
I'm not 100% sure if switching from DateTime to SysTime fixes a 
bug, introduces a bug, or doesn't make any difference. As far as 
I can tell, it doesn't change anything, because you're not 
dealing with different time zones.
    
    
More information about the Digitalmars-d-learn
mailing list