Yesterday and Today – The Daily WTF

There is poor date handling, which often involves re-engineering the date handling itself, often using strings or integers along the way. There is also the poor date handling used by the date handling framework, which still manages to be poor.

This C# comes from TheColonial.

public static void ToStartofCurrDay(ref DateTime dt)

      dt = dt.Subtract(dt.TimeOfDay);

Now, this is not passionately. And sure enough, if you go searching the internet for “how to round/truncate a datetime in C#”, you’ll see answers that solve the arbitrary rounding problem of any interval, and the code is complicated and ugly, like dates.

But that’s only if you go looking for it. If you actually read the documents, DateTime the guy has a Date property, you guessed it- returns a date with the time set to midnight, exactly the same as this code.

I don’t like it, but it’s not WTF. Here we have a function that reverses the current DateTime ua 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 now, we don’t have any use practical function we implemented, we just repeat the same operation: dt.Subtract(dt.TimeOfDay). Then we create a TimeSpan and subtract that, which puts us at the latest possible time of the previous day – exactly one beat before midnight.

And yes, it is one tick, where each tick is 100ns. So, ToEndofPrevDay returns the date and time ie one tick before midnight today.

Then we have ToEndofCurrDaywhich uses overloaded - instead of operator Subtract function, which is safe: consistency is the tramp of small minds and programmers. Clearly they don’t conform to indentation, so why conform to style? Then they add 23 hours, 59 minutes, 59 seconds and 999 milliseconds.

Which is to say, the end of today is one millisecond before midnight the next day. End yesterday however, it is 100 nanoseconds before midnight.

Now, does this gap actually matter? Almost certainly not. Heck, a sort order or something might help. But does this gap bother me? Oh, you better believe it is. The end of yesterday and the end of today are not anchored to the same time – tomorrow, today will “end” a full 9900 nanoseconds earlier than today. That sentence might not make a lot of sense, but that’s what happens when you’re dealing with date-handling code.

[Advertisement]

Otter – Secure your servers automatically without the need to log into the command line. Get started today!

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *