12,449,440 members (62,684 online)
Alternative Tip/Trick
alternative version

6.2K views
4 bookmarked
Posted

# Partial DateTime Object Equality

, 15 Mar 2012 CPOL
 Rate this:
This is an alternative for "Partial DateTime Object Equality"

## Introduction

I herein refer to the original post of http://www.codeproject.com/Tips/148065/Partial-DateTime-Object-Equality and offer some alterantive approch.

You may employ more of the native C# support for this partial DateTime Equality function:

1. Define the enum flags with bit shift operator instead of manually calculated powers of two values
3. Use boolean logic to directly calculate the boolean result instead of over the re-calculation of some flag values.

## Using the code

### Alternative definition of the Equality Mask:

Use bit-shift instead of hardcoded values.

OriginalAlternative
```  1  [Flags]
2  public enum DatePartFlags
3  {
4
5
6     Ticks=0,
7     Year=1,
8     Month=2,
9     Day=4,
10     Hour=8,
11     Minute=16,
12     Second=32,
13     Millisecond=64
14  };
```
```  1  [Flags]
3  {
4      // make conformant to MS guidelines again:
5      // define a meaningful 0-value
6      Ticks       = 0,
7      Year        = (1<<0),
8      Month       = (1<<1),
9      Day         = (1<<2),
10      Hour        = (1<<3),
11      Minute      = (1<<4),
12      Second      = (1<<5),
13      Millisecond = (1<<6),
14
15      Full        = Ticks,
16      Date        = Day|Month|Year,
17      Time        = Hour|Minute|Second|Millisecond,
18  };
```

### An alternative Equals method:

Use the HasFlag() method that is defined on all enum types.

In addition, you might use the direct logic that allows for shortcut evaluation for the first failure (usage of && and ||).

```  1  public static bool Equal(this DateTime now, DateTime then, DtMask mask)
2  {
3      // Caution: 0-value always match in HasFlag(), use therefore "=="
12  }
```

## History

 1 Initial version 1.1 added more refrences to the original post 1.2 Adjusted enum and Equals method by taking Jani's input into count: Full == Ticks, take Milliseconds into Time check

## Share

 Founder eXternSoft GmbH Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

## You may also be interested in...

 Pro Pro

 First Prev Next
 My vote of 5 Jani Giannoudis14-Mar-12 4:20 Jani Giannoudis 14-Mar-12 4:20
 Re: My vote of 5 Andreas Gieriet15-Mar-12 11:24 Andreas Gieriet 15-Mar-12 11:24
 Last Visit: 31-Dec-99 18:00     Last Update: 26-Aug-16 3:29 Refresh 1