time difference - beautify my code
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 3 02:51:37 PDT 2015
On Thursday, July 02, 2015 19:42:57 anonymous via Digitalmars-d-learn wrote:
> 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
> private static bool sessionIsCurrent(long t)
> {
> immutable dateTime = SysTime(unixTimeToStdTime(t));
> return (Clock.currTime - dateTime) < 12.hours;
> }
I'm not sure if immutable works with SysTime. It didn't used to (due to
issues with the compiler, not the type itself). Also, it's probably not a
good idea to sue the name dateTime for a variable of type SysTime.
> You may want to check that t is not in the future.
Depending on what exactly the OP is looking for, they may want to do
something more like
private static bool sessionIsCurrent(long t)
{
auto st = SysTime(unixTimeToStdTime(t));
return abs(Clock.currTime - dateTime) < 12.hours;
}
With what you have, it'll return true not only if the given time was less
than 12 hours ago, but it will return true if it's at any point in the
future. Now, that may be exactly what the OP wants, but checking if "the
current time is further than 12 hours from the given time" could be taken
to mean that if it's more than 12 hours past the current time, the function
shouldn't return true. Only the OP knows exactly what they meant though.
> 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.
When you convert to a DateTime from a SysTime, you're getting the equivalent
year-date-month and hour-minute-second that the SysTime represents in the
time zone that it's set to (LocalTime by default). So, you lose subsecond
precision (which likely wouldn't matter in this case), and you lose the time
zone, so you do potentially have to take that into account when converting
back, but if everything is in LocalTime, that's usually not a problem. The
main problem would be if the time in question were during a DST switch, in
which case, you might not get the same SysTime back (even ignoring the
fractional seconds).
So, in general, while it can be useful to convert a SysTime to a DateTime
(especially if you want all of the units split out), it's generally better
not to convert a DateTime to a SysTime unless you actually need to
(primarily because DST screws with things).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list