Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse for only a Time parameter?

Tags:

c#

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.

like image 288
Isaiah Nelson Avatar asked Mar 06 '26 01:03

Isaiah Nelson


2 Answers

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:

  • It's almost never appropriate to ignore the return value from 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 rare
  • Please try to avoid code of the form:

    if (condition)
        return true;
    else
        return false;
    

    This is much more clearly written as:

    return condition;
    
like image 157
Jon Skeet Avatar answered Mar 09 '26 12:03

Jon Skeet


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):

  • 08:09:00 AM
  • 08:09 AM
  • 8:30 AM
  • 8:30:59

You can check it here

Hope this helps

like image 43
Jean-Francois Bertrand Avatar answered Mar 09 '26 10:03

Jean-Francois Bertrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!