There's bad date handling, which frequently involves reinventing date handling yourself, frequently using strings or integers along the way. Then there's the bad date handling which uses the date handling framework, and still manages to be bad.

This C# comes from TheColonial.

public static void ToStartofCurrDay(ref DateTime dt)
{
      dt = dt.Subtract(dt.TimeOfDay);
}

Now, this isn't terrible. And certainly, if you go searching on the Internet for "how to round/truncate a datetime in C#" you're going to see answers that solve the arbitrary problem of rounding to any interval, and the code is complicated and ugly, like dates.

But that's only if you go searching. If you actually read the docs, the DateTime type has a Date property, which you guessed it- returns the date with the time set to midnight, the same exact thing that this code does.

I don't like it, but that's not the WTF. What we have here is a function that turns the current DateTime into a DateTime at midnight of the same day.

So what functions does this developer implement next?

public static void ToEndofPrevDay(ref DateTime dt)
{
  dt = dt.Subtract(dt.TimeOfDay);
        TimeSpan ts = new TimeSpan(1);
   dt = dt.Subtract(ts);
}

public static void ToEndofCurrDay(ref DateTime dt)
{
 dt = dt - dt.TimeOfDay;
   dt = dt.AddHours(23);
   dt = dt.AddMinutes(59);
 dt = dt.AddSeconds(59);
       dt = dt.AddMilliseconds(999);                               
}

So, right off the bat, we don't use the handy function we implemented, we just redo the same operation: dt.Subtract(dt.TimeOfDay). Then we create a TimeSpan and subtract that, which puts us at the latest possible time on the previous day- exactly one tick before midnight.

And yes, that's one tick, where each tick is 100ns. So, ToEndofPrevDay returns a datetime that is one tick before midnight of today.

Then we have ToEndofCurrDay, which uses the overloaded - operator instead of the Subtract function, which sure: consistency is the hobgoblin of tiny minds and programmers. Clearly they're not consistent with indentation, so why be consistent with style? Then they add 23 hours, 59 minutes, 59 seconds, and 999 milliseconds.

Which is to say, the end of the current day is one millisecond before midnight of the next day. The end of yesterday however, is 100 nanoseconds before midnight.

Now, does this gap actually matter? Almost certainly not. Hell, it might even help the sort order or something. But does this gap bother me? Oh you better believe it does. The end of yesterday and the end of today are not anchored against the same time- tomorrow, today will "end" a full 9,900 nanoseconds earlier than it did today. That sentence might not make a huge amount of sense, but that's what happens when you deal with date handling code.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!