How to Convert string "07:35" (HH:MM) to TimeSpan
Asked Answered
C

4

72

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);
Charbonnier answered 23/6, 2014 at 14:55 Comment(2)
Use TimeSpan.Parse. msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspxAcrocarpous
possible duplicate of Parse string to TimeSpanAcrocarpous
D
160

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
    }
    
Durwood answered 30/6, 2014 at 19:12 Comment(6)
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 avoidedDyspnea
I can't parse a time over than 24 hoursPinna
@Pinna - 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.Durwood
what if its 7:35 AM to TimeSpanProtractor
TimeSpan.TryParseExact("7:35 AM", "h:mm tt", CultureInfo.InvariantCulture, out TimeSpan startDate); does not workProtractor
@Protractor - 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.Durwood
M
13

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.

Meredith answered 23/6, 2014 at 14:58 Comment(0)
G
6

Use TimeSpan.Parse to convert the string

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

Googins answered 23/6, 2014 at 14:57 Comment(0)
I
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.

Ideology answered 18/6, 2016 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.