65

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.

Right now I have a "old fashion style":

string stringTime = "07:35";
string[] values = stringTime.Split(':');

TimeSpan ts = new TimeSpan(values[0], values[1], 0);
VAAA
  • 14,531
  • 28
  • 130
  • 253

4 Answers4

155

Data Types

For the string "07:35" given in the question, there are three possible data types to choose from:

TimeSpan

  • Primarily intended for a duration of elapsed time.
  • Sometimes used for a time-of-day, especially prior to .NET 6.
  • Range: -10675199.02:48:05.4775808 to 10675199.02:48:05.4775807
  • Magnitudes of 24 hours or larger are represented in terms of standard (24 hour) days, which are separated by a period in the default string representation.
  • Negative values represent moving backwards in time.

TimeOnly

  • Intended for a time-of-day value, without any date component.
  • Range: 00:00:00.000000 to 23:59:59.9999999
  • Available since .NET 6. For older .NET, consider a polyfill library such as Portable.System.DateTimeOnly.

DateTime

  • Primarily intended for a date combined with a time.
  • Range: 0001-01-01 00:00:00.0000000 to 9999-12-31 23:59:59.9999999
  • Sometimes used for representing time-only values, by using an arbitrary date such as 0001-01-01 or 2000-01-01, etc. When doing so, it's important to disregard the date in all usages. Generally, this was done in older software to support parsing am/pm components, but is no longer necessary since .NET 6.

Parsing

Methods

All three data types support the following methods:

  • Parse - Attempts to parse using a variety of known formats. Throws an exception if parsing does not succeed.

  • TryParse - Like Parse, but returns false if the parsing does not succeed. Useful for validation logic.

  • ParseExact - Attempts to parse using a specific format. Throws an exception if parsing does not succeed.

  • TryParseExact - Like ParseExact, but returns false if parsing does not succeed. Useful for validation logic.

Format Specifiers (tokens)

The ParseExact and TryParseExact methods require a format specification, which can be either in a standard form represented by a a single character, or a custom form represented by multiple characters. The format strings differ by data type.

  • TimeOnly and DateTime use the standard or custom date and time format strings.

    • "07:35" can be parsed with the custom "HH:mm" format in all cultures, including the InvariantCulture.
    • "07:35" can also be parsed with the standard "t" format in many cultures, including the InvariantCulture.
  • TimeSpan uses the standard or custom time span format strings.

    • "07:35" can be parsed with the custom @"hh\:mm" (or "hh\\:mm") format in most cultures, including the InvariantCulture.
    • "07:35" can also be parsed with the standard "c" or "g" formats in many cultures, including the InvariantCulture.

Examples

I'll demonstrate both TimeSpan and TimeOnly. (Generally speaking, DateTime is no longer needed for such strings.) In all cases, be sure to import both System and System.Globalization in your using statements, unless you're already importing them implicitly.

  • Flexible parsing (using current culture):

    TimeSpan duration = TimeSpan.Parse("07:35");
    
    TimeOnly time = TimeOnly.Parse("07:35");
    
  • Fixed parsing (performant, using invariant culture):

    TimeSpan duration = TimeSpan.ParseExact("07:35", @"hh\:mm", 
    CultureInfo.InvariantCulture);
    
    TimeOnly time = TimeOnly.ParseExact("07:35", "HH:mm", 
    CultureInfo.InvariantCulture);
    
  • Flexible parsing for validation (using current culture):

    TimeSpan duration;
    if (!TimeSpan.TryParse("07:35", out duration))
    {
        // handle validation error
    }
    
    TimeOnly time;
    if (!TimeOnly.TryParse("07:35", out time))
    {
        // handle validation error
    }
    
  • Fixed parsing for validation (performant, using invariant culture):

    TimeSpan duration;
    if (!TimeSpan.TryParseExact("07:35", @"hh\:mm", 
    CultureInfo.InvariantCulture, out duration))
    {
        // handle validation error
    }
    
    TimeOnly time;
    if (!TimeOnly.TryParseExact("07:35", "HH:mm", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
    {
        // handle validation error
    }
    
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 3
    `DateTime.TryParse` is quite slow, `DateTime.TryParseExact` is miles quicker. My understanding is `TryParse` tries a set of patterns to see if any match, if the format you're after is at the bottom of that list, its a substantial overhead that is easily avoided – Joe Jun 30 '14 at 19:20
  • I can't parse a time over than 24 hours – alansiqueira27 Aug 16 '18 at 15:59
  • @alansiqueira27 - `TimeSpan` can *represent* >= 24 hours, but as a string it treats them as "days". So `ParseExact` etc. cannot parse them. It would be nice if there was some other token to allow it, but alas there is not. Instead one can parse such strings manually, such as shown [in this answer](https://stackoverflow.com/questions/2728321/how-to-parse-string-with-hours-greater-than-24-to-timespan). – Matt Johnson-Pint Aug 16 '18 at 16:48
  • what if its `7:35 AM` to TimeSpan – Tonto Jul 11 '23 at 14:25
  • `TimeSpan.TryParseExact("7:35 AM", "h:mm tt", CultureInfo.InvariantCulture, out TimeSpan startDate);` does not work – Tonto Jul 11 '23 at 15:46
  • @Tonto - My original answer suggested `DateTime` for such a format, not `TimeSpan`. Nonetheless, today I would recommend `TimeOnly` for such values. I've revised the entire answer to cover this. Thanks. – Matt Johnson-Pint Jul 14 '23 at 17:57
12

Try

var ts = TimeSpan.Parse(stringTime);

With a newer .NET you also have

TimeSpan ts;

if(!TimeSpan.TryParse(stringTime, out ts)){
     // throw exception or whatnot
}
// ts now has a valid format

This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.

radbyx
  • 9,352
  • 21
  • 84
  • 127
faester
  • 14,886
  • 5
  • 45
  • 56
6

Use TimeSpan.Parse to convert the string

http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx

adjan
  • 13,371
  • 2
  • 31
  • 48
3

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37