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?
(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:
Another alternative might be to make them extension methods:
I’d definitely make them static either way 🙂