Fastest way to compare dates using two unix timestamps?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jul 26 13:14:37 PDT 2013


On Friday, July 26, 2013 21:51:39 Gary Willoughby wrote:
> I'm writing a program that deals a lot with dates in unix
> timestamp format. I need to 'normalise' this timestamp to only
> give me the date and not the time. To do this i thought of using
> only midnight on that day.
> 
> Here is the first attempt to normalise these dates:
> 
> protected uint trimUnixToDate(uint unixTimeStamp)
> {
> auto time = SysTime(unixTimeToStdTime(unixTimeStamp));
> auto offset = time.dstInEffect ? 3600 : 0;
> 
> return (unixTimeStamp - (unixTimeStamp % 86400)) - offset;
> }
> 
> While this works (for my timezone and DST settings) it is slow.
> Is there a faster way to do this?
> 
> Or how can i compare two timestamps and only compare the date
> contained within, not the time?

The fastest way would probaby be to just divide by the number of seconds in a 
day and compare those. And if you want it normalized to midnight rather than 
to just compare the days, then multiply the value by the number of seconds in 
a day again. And if you don't want to have to have a magic number sitting 
there, you can do

enum secondsInADay = convert!("days", "seconds")(1);

Now, if you need to worry about the date in your local time zone rather than 
UTC (which it looks you might be trying to do given what you're doing with 
dstInEffect), then the fastest thing to do would probably be something like

immutable stdTime = unixTimeToStdTime(unixTime);
enum hnsecsInDay = convert!("days", "hnsecs")(1);
immutable localMidnight = LocalTime().utcToTZ(stdTime) / hnsecsInDay *
 hnsecsInDay;
immutable stdMidnight = LocalTime().tzToUTC(localMidnight);
immutable unixMidnight = stdTimeToUnixTime(stdMidnight);

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list