Question

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?

Was it helpful?

Solution

(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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top