I am writing a service that calls a method at 4pm and 5am. I would like to keep these times from being hard coded and so I would like to have put them in my appconfig.
Here is the code I have:
public bool CheckTime()
{
DateTime startTime;
DateTime endTime;
DateTime.TryParse(ConfigurationManager.AppSettings["ProcessingStartTime"], out startTime);
DateTime.TryParse(ConfigurationManager.AppSettings["ProcessingEndTime"], out endTime);
if(DateTime.Now.TimeOfDay.Equals(startTime) || DateTime.Now.TimeOfDay.Equals(endTime))
return true;
else
return false;
}
But, since I only want to store the time as a string (something as easy as “4:00pm”) how do I parse and encapsulate JUST the time in a DateTime object? Or is there another object? I don’t care about the date, it just has to be M-F of any given week of any given year.
Thanks guys.
You can use
TryParseExactwith an appropriate format string, and then ignore the date. There’s no nice encapsulation for “just a time” in .NET. However, there’s an alternative – I’ve been working hard on Noda Time which has theLocalTimetype for just this purpose:Two side-notes:
DateTime.TryParse(or any otherTryParsemethod) – do you really want to useDateTime.MinValueif there’s a problem with the data? There are cases where the default value is appropriate, but they’re pretty rarePlease try to avoid code of the form:
This is much more clearly written as: