Ya know, I would probably write that code like this, because it's easier to read the if statement. It calls the extension method shown at the end of this solution:
if (cat != null)
{
DateTime start = (cat.StartTime.HasValue) ? cat.StartTime.Value.SetSeconds() : new DateTime(0);
DateTime end = (cat.EndTime.HasValue) ? cat.EndTime.Value.SecSeconds() : new DateTime(0);
DateTime now = DateTime.Now;
bool inRange = (start <= now && end >= now);
if (!(start <= now && end >= now))
{
flpCategories.Controls.Remove(ctrl);
}
}
As for showing a control when
inRange
is true, simply set the visible flag for the control. Since you didn't specify the framework (WinForms, WPF, ASP.Net), I'll leave it to you to find the appropriate way to do that.
If you're interested, I wrote a tip/trick that allows you to compare the desired parts of two
DateTime
objects:
Partial DateTime Object Equality[
^]
And btw, here's a handy extension method for setting the seconds from a DateTime. calling it with no parameters will automatically return the date value with the seconds and milliseconds to 0.
public static DateTime SetSeconds(this DateTime date, double secs=0, double millisecs=0)
{
return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, secs, millisecs, date.Kind);
}