Comparing the binary representation of DateTime in C#

Viewed 285

I have a DateTime represented as long (8 bytes), that came from DateTime.ToBinary(), let's call it dateTimeBin. Is there an optimal way of dropping the Time information (I only care for the date) so I can compare it to a start of day? Lets say we have this sample value as a start of day.

DateTime startOfDay = new DateTime(2020,3,4,0,0,0);
long startOfDayBin = startOfDay.ToBinary();

I obviously know I can always convert to a DateTime object then get the date component. However, this operation is going to happen billions of times and every little performance tweak helps.

  • Is there an efficient way of extracting the Date info of dateTimeBin without converting it to DateTime? Or any arithmetic operation on the long that will return the date only?
  • Is there a way to match startOfDay (or startOfDayBin) and dateTimeBin if they have the same date components?
  • Is there a way to see if (dateTimeBin >= startOfDayBin), I don't think the long comparison is valid.

N.B. all the dates are UTC

1 Answers

Since you are working only with UTC dates - makes sense to use DateTime.Ticks instead of DateTime.ToBinary, because former has relatively clear meaning - number of ticks since epoch, just like the unix time, the only difference is unix time interval is second and not tick (where tick is 1/10.000.000 of a second), and epoch is midnight January 1st of 0001 year and not year 1970. While ToBinary only promises that you can restore original DateTime value back and that's it.

With ticks it's easy to extract time and date. To extract time, you need to remainder of division of ticks by number of ticks in a full day, so

long binTicks = myDateTime.Ticks;
long ticksInDay = 24L * 60 * 60 * 10_000_000;
long time = binTicks % ticksInDay;

You can then use convert that to TimeSpan:

var ts = TimeSpan.FromTicks(time);

for convenience, or use as is. The same with extracting only date: just substract time

long date = binTicks - (binTicks % ticksInDay);

Regular comparision (dateTimeBin >= startOfDayBin) in also valid for tick values.

Related