You aren't that far off...
There is a slight issue with your code as it stands, everytime you call DateTime.Now
the time would have changed - you need to capture that instance of time when the service is triggered i.e.
var instant = DateTime.Now;
DateTime silenceModeFrom = new DateTime(instant.Year, instant.Month, instant.Day, int.Parse(doc.XPathSelectElement("//SurveilanceServiceConfig/SilenceModeTimeFrom").Value), 00, 00);
DateTime silenceModeTo = silenceModeFrom.AddHours(int.Parse(doc.XPathSelectElement("//SurveilanceServiceConfig/SilenceModeTimeHours").Value));
bool silence = instant.TimeOfDay >= silenceModeFrom.TimeOfDay && instant <= silenceModeTo;
Looking at this code though, your time window appears wrong. You aren't really interested in the Date
at all here - it's really just the time. Therefore, anything between 23:00hrs - 07:00hrs is considered the "silent" period i.e.
int curHour = DateTime.Now.Hour;
int silenceStartHour = int.Parse(doc.XPathSelectElement("//SurveilanceServiceConfig/SilenceModeTimeFrom").Value);
int silenceEndHour = int.Parse(doc.XPathSelectElement("//SurveilanceServiceConfig/SilenceModeTimeHours").Value);
bool silence = curHour > silenceStartHour || curHour < silenceEndHour;
The logic for determining whether you are in the silent period can be improved slightly to account for a range that is all in one day, or a range that is split over midnight.
bool silence = silenceStartHour <= silenceEndHour
? (curHour >= silenceStartHour && curHour < silenceEndHour)
: (curHour >= silenceStartHour || curHour < silenceEndHour);