Click here to Skip to main content

Partial DateTime Object Equality

While working on a future article, I decided I need to be able to compare two DateTime objects based on any property I chose. In other words, if I wanted to see if two DateTimes objects had the same hour and minute, but didn't care about the rest of the values (year, month, etc) I would need to code it myself. To accomplish this, I wrote a couple of extension methods to satisfy the requirement.

[Flags]
public enum DatePartFlags {Ticks=0, Year=1, Month=2, Day=4, Hour=8, Minute=16, Second=32, Millisecond=64 };
public static class ExtensionMethods
{
    private static bool FlagIsSet(DatePartFlags flags, DatePartFlags flag)
    {
        bool isSet = ((flags & flag) == flag);
        return isSet;
    }
 
    public static bool Equal(this DateTime now, DateTime then, DatePartFlags flags)
    {
        bool isEqual = false;
        if (flags == DatePartFlags.Ticks)
        {
            isEqual = (now == then);
        }
        else
        {
            DatePartFlags equalFlags = DatePartFlags.Ticks;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Year) && now.Year == then.Year) ? DatePartFlags.Year : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Month) && now.Month == then.Month) ? DatePartFlags.Month : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Day) && now.Day == then.Day) ? DatePartFlags.Day : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Hour) && now.Hour == then.Hour) ? DatePartFlags.Hour : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Minute) && now.Minute == then.Minute) ? DatePartFlags.Minute : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Second) && now.Second == then.Second) ? DatePartFlags.Second : 0;
            equalFlags |= (FlagIsSet(flags, DatePartFlags.Millisecond) && now.Millisecond == then.Millisecond) ? DatePartFlags.Millisecond : 0;
            isEqual = (flags == equalFlags);
        }
        return isEqual;
    }
}

Usage is as follows:

private void LoopUntilItHurts()
{
    DatePartFlags equalityFlags = DatePartFlags.Minute | DatePartFlags.Second;
    DateTime now = DateTime.Now;
    DateTime then = DateTime.Now;
    bool waiting = false;
 
    while (true)
    {
        now = DateTime.Now;
        if (!waiting)
        {
            int difference = now.Minute % 5;
            then = now.Add(new TimeSpan(0, 0, 1, 0, 0));
            waiting = true;
        }
 
        if (now.Equal(then, equalityFlags))
        {
            waiting = false;
            // it's time to do something important    
        }
        else
        {
            // sit and spin
            Thread.Sleep(1000);
        }
    }
}

Web02 | 2.8.160204.4 | Advertise | Privacy
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service