views:

193

answers:

1

I need to test that a DateTime is at the beginning of a some unit of time for various units. This is the code I'm using right now:

/// ignoring milliseconds all the way down

bool IsMinute(DateTime dt)
{
  return dt.Second == 0;
}

bool IsHour(DateTime dt) 
{
  return dt.Second == 0 && dt.Minute == 0;
}  

bool IsDay(DateTime dt) 
{
  return dt.Date == dt;
}

bool IsMonth(DateTime dt) 
{
  return dt.Date == dt && dt.Day == 1;
}

bool IsYear(DateTime dt) 
{
  return dt.Date == dt && dt.DayOfYear == 1;
}

Any ideas for improvements?

+7  A: 

(EDIT: IsMonth is fine because it first checks that it's just a date.)

You might want to chain these together - for example, your IsMinute should probably check for milliseconds. Rather than add that test to IsHour as well, just make IsHour check for IsMinute first. Chaining is simple:

bool IsHour(DateTime dt) 
{
    return IsMinute(dt) && dt.Minute == 0;
}

Another alternative might be to make them extension methods:

public static bool IsHour(this DateTime dt) 
{
    return dt.IsMinute() && dt.Minute == 0;
}

I'd definitely make them static either way :)

Jon Skeet
If any of them reused more than a single clause the chaining would be really good. Is it is... I'm not sure how much it would gain from it.
BCS
@BCS: Apologies, IsMonth is fine. Will edit answer.
Jon Skeet