Click here to Skip to main content
15,884,794 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Partial DateTime Object Equality

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
6 Feb 2015CPOL 6.7K   2  
This is an alternative for "Partial DateTime Object Equality"

Introduction

I was messing around with some code that used this tip, and came up with an alternative.

Using the code

We still compare the flags, but instead of creating a new flag variable, we create a string, convert it to a 64-bit integer, and compare the resulting integers for the dates in question. I'm sure this isn't as efficient, but it is another way to look at it.

C#
public static bool PartiallyEqual2
(this DateTime then, DateTime now, DatePartFlags flags = DatePartFlags.Ticks)
{
    bool isEqual = false;
    if (flags == DatePartFlags.Ticks)
    {
        isEqual = (now == then);
    }
    else
    {
        StringBuilder compareStr = new StringBuilder();
        compareStr.Append(flags.HasFlag(DatePartFlags.Year)       ?"yyyy":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Month)      ?"MM":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Day)        ?"dd":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Hour)       ?"HH":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Minute)     ?"mm":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Second)     ?"ss":"");
        compareStr.Append(flags.HasFlag(DatePartFlags.Millisecond)?"fff":"");
        isEqual = now.ConvertToInt64
    (compareStr.ToString()) == then.ConvertToInt64(compareStr.ToString());
    }
    return isEqual;
}

public static Int64 ConvertToInt64(this DateTime thisDate, string format)
{
    Int64 dateValue = Convert.ToInt64(thisDate.ToString(format));
    return dateValue;
}

History

  • 6th February, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
-- There are no messages in this forum --