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 TryParseExact with 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 the LocalTime type for just this purpose:
// "Traditional" way
LocalTime time;
if (LocalTime.TryParseExact(text, "h:mmtt", out time))
{
...
}
// Preferred way
private static readonly LocalTimePattern TimePattern =
LocalTimePattern.CreateWithInvariantInfo("h:mmtt");
...
ParseResult<LocalTime> parseResult = TimePattern.Parse(text);
if (parseResult.Success)
{
LocalTime time = parseResult.Value;
...
}
Two side-notes:
DateTime.TryParse (or any other TryParse method) - do you really want to use DateTime.MinValue if 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:
if (condition)
return true;
else
return false;
This is much more clearly written as:
return condition;
I've had a hard time doing the tryparse (even w/ TryParseExact) so I wrote a regex:
Regex checkTime = new Regex(@"^(?i)(0?[1-9]|1[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?( AM| PM)?$");
And you can validate your time with this:
checkTime.IsMatch(str);
This will work for these format (case insensitive):
You can check it here
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With