TimeSpan.TryParse Method

Definition

Converts the specified string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

Overloads

TryParse(String, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

Converts the span representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, TimeSpan)

Converts the span representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.

TryParse(String, TimeSpan)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

C#
public static bool TryParse(string s, out TimeSpan result);
C#
public static bool TryParse(string? s, out TimeSpan result);

Parameters

s
String

A string that specifies the time interval to convert.

result
TimeSpan

When this method returns, contains an object that represents the time interval specified by s, or Zero if the conversion failed. This parameter is passed uninitialized.

Returns

true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is null or Empty, has an invalid format, represents a time interval that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

Examples

The following example uses the TryParse method to create TimeSpan objects from valid TimeSpan strings and to indicate when the parse operation has failed because the time span string is invalid.

C#
using System;

public class TryParse
{
   private static void ParseTimeSpan(string intervalStr)
   {
      // Write the first part of the output line.
      Console.Write( "{0,20}   ", intervalStr );

      // Parse the parameter, and then convert it back to a string.
      TimeSpan intervalVal; 
      if (TimeSpan.TryParse(intervalStr, out intervalVal)) 
      {
         string intervalToStr = intervalVal.ToString();
  
         // Pad the end of the TimeSpan string with spaces if it 
         // does not contain milliseconds.
         int pIndex = intervalToStr.IndexOf(':');
         pIndex = intervalToStr.IndexOf('.', pIndex);
         if (pIndex < 0)
            intervalToStr += "        ";
   
         Console.WriteLine("{0,21}", intervalToStr);
         // Handle failure of TryParse method.
      }
      else
      {
         Console.WriteLine("Parse operation failed.");
      }
   } 
   
   public static void Main()
   {
        Console.WriteLine( "{0,20}   {1,21}", 
            "String to Parse", "TimeSpan" );    
        Console.WriteLine( "{0,20}   {1,21}", 
            "---------------", "---------------------" );    

        ParseTimeSpan("0");
        ParseTimeSpan("14");
        ParseTimeSpan("1:2:3");
        ParseTimeSpan("0:0:0.250");
        ParseTimeSpan("10.20:30:40.50");
        ParseTimeSpan("99.23:59:59.9999999");
        ParseTimeSpan("0023:0059:0059.0099");
        ParseTimeSpan("23:0:0");
        ParseTimeSpan("24:0:0");
        ParseTimeSpan("0:59:0");
        ParseTimeSpan("0:60:0");
        ParseTimeSpan("0:0:59");
        ParseTimeSpan("0:0:60");
        ParseTimeSpan("10:");
        ParseTimeSpan("10:0");
        ParseTimeSpan(":10");
        ParseTimeSpan("0:10");
        ParseTimeSpan("10:20:");
        ParseTimeSpan("10:20:0");
        ParseTimeSpan(".123");
        ParseTimeSpan("0.12:00");
        ParseTimeSpan("10.");
        ParseTimeSpan("10.12");
        ParseTimeSpan("10.12:00");
   }
}
//            String to Parse                TimeSpan
//            ---------------   ---------------------
//                          0        00:00:00
//                         14     14.00:00:00
//                      1:2:3        01:02:03
//                  0:0:0.250        00:00:00.2500000
//             10.20:30:40.50     10.20:30:40.5000000
//        99.23:59:59.9999999     99.23:59:59.9999999
//        0023:0059:0059.0099        23:59:59.0099000
//                     23:0:0        23:00:00
//                     24:0:0   Parse operation failed.
//                     0:59:0        00:59:00
//                     0:60:0   Parse operation failed.
//                     0:0:59        00:00:59
//                     0:0:60   Parse operation failed.
//                        10:   Parse operation failed.
//                       10:0        10:00:00
//                        :10   Parse operation failed.
//                       0:10        00:10:00
//                     10:20:   Parse operation failed.
//                    10:20:0        10:20:00
//                       .123   Parse operation failed.
//                    0.12:00        12:00:00
//                        10.   Parse operation failed.
//                      10.12   Parse operation failed.
//                   10.12:00     10.12:00:00

Remarks

For more information about this API, see Supplemental API remarks for TimeSpan.TryParse.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the span representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.

C#
public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider? formatProvider, out TimeSpan result);
C#
public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result);

Parameters

input
ReadOnlySpan<Char>

A span containing the characters representing the time interval to convert.

formatProvider
IFormatProvider

An object that supplies culture-specific formatting information.

result
TimeSpan

When this method returns, contains an object that represents the time interval specified by input, or Zero if the conversion failed. This parameter is passed uninitialized.

Returns

true if input was converted successfully; otherwise, false. This operation returns false if the input parameter is null or Empty, has an invalid format, represents a time interval that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

TryParse(ReadOnlySpan<Char>, TimeSpan)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the span representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

C#
public static bool TryParse(ReadOnlySpan<char> s, out TimeSpan result);

Parameters

s
ReadOnlySpan<Char>

A span containing the characters representing the time interval to convert.

result
TimeSpan

When this method returns, contains an object that represents the time interval specified by s, or Zero if the conversion failed. This parameter is passed uninitialized.

Returns

true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is null or Empty, has an invalid format, represents a time interval that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

TryParse(String, IFormatProvider, TimeSpan)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.

C#
public static bool TryParse(string input, IFormatProvider formatProvider, out TimeSpan result);
C#
public static bool TryParse(string? input, IFormatProvider? formatProvider, out TimeSpan result);

Parameters

input
String

A string that specifies the time interval to convert.

formatProvider
IFormatProvider

An object that supplies culture-specific formatting information.

result
TimeSpan

When this method returns, contains an object that represents the time interval specified by input, or Zero if the conversion failed. This parameter is passed uninitialized.

Returns

true if input was converted successfully; otherwise, false. This operation returns false if the input parameter is null or Empty, has an invalid format, represents a time interval that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

Examples

The following example defines an array of CultureInfo objects, and uses each object in calls to the TryParse(String, IFormatProvider, TimeSpan) method to parse the elements in a string array. The example illustrates how the conventions of a specific culture influence the formatting operation.

C#
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "6", "6:12", "6:12:14", "6:12:14:45", 
                          "6.12:14:45", "6:12:14:45.3448", 
                          "6:12:14:45,3448", "6:34:14:45" };
      CultureInfo[] cultures = { new CultureInfo("en-US"), 
                                 new CultureInfo("ru-RU"),
                                 CultureInfo.InvariantCulture };
      
      string header = String.Format("{0,-17}", "String");
      foreach (CultureInfo culture in cultures)
         header += culture.Equals(CultureInfo.InvariantCulture) ? 
                      String.Format("{0,20}", "Invariant") :
                      String.Format("{0,20}", culture.Name);

      Console.WriteLine(header);
      Console.WriteLine();
      
      foreach (string value in values)
      {
         Console.Write("{0,-17}", value);
         foreach (CultureInfo culture in cultures)
         {
            TimeSpan interval = new TimeSpan();
            if (TimeSpan.TryParse(value, culture, out interval))
               Console.Write("{0,20}", interval.ToString("c"));
            else
               Console.Write("{0,20}", "Unable to Parse");
         }
         Console.WriteLine();                                
      }
   }
}
// The example displays the following output:
//    String                          en-US               ru-RU           Invariant
//    
//    6                          6.00:00:00          6.00:00:00          6.00:00:00
//    6:12                         06:12:00            06:12:00            06:12:00
//    6:12:14                      06:12:14            06:12:14            06:12:14
//    6:12:14:45                 6.12:14:45          6.12:14:45          6.12:14:45
//    6.12:14:45                 6.12:14:45          6.12:14:45          6.12:14:45
//    6:12:14:45.3448    6.12:14:45.3448000     Unable to Parse  6.12:14:45.3448000
//    6:12:14:45,3448       Unable to Parse  6.12:14:45.3448000     Unable to Parse
//    6:34:14:45            Unable to Parse     Unable to Parse     Unable to Parse

Remarks

For more information about this API, see Supplemental API remarks for TimeSpan.TryParse.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0