Export (0) Print
Expand All

TimeSpan.TryParse Method (String, TimeSpan)

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static bool TryParse(
	string s,
	out TimeSpan result
)

Parameters

s
Type: System.String

A string that specifies the time interval to convert.

result
Type: System.TimeSpan

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

Return Value

Type: System.Boolean
true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is null or String.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.

The TryParse method is like the TimeSpan.Parse(String) method, except that it does not throw an exception if the conversion fails.

The s parameter contains a time interval specification in the form:

[ws][-]{ d | d.hh:mm[:ss[.ff]] | hh:mm[:ss[.ff]] }[ws]

Elements in square brackets ([ and ]) are optional. One selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required. The following table describes each element.

Element

Description

ws

Optional white space.

-

An optional minus sign, which indicates a negative TimeSpan.

d

Days, ranging from 0 to 10675199.

.

A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.

hh

Hours, ranging from 0 to 23.

:

The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.

mm

Minutes, ranging from 0 to 59.

ss

Optional seconds, ranging from 0 to 59.

.

A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.

ff

Optional fractional seconds, consisting of one to seven decimal digits.

The components of s must collectively specify a time interval that is greater than or equal to TimeSpan.MinValue and less than or equal to TimeSpan.MaxValue.

The Parse(String) method tries to parse s by using each of the culture-specific formats for the current culture.

Notes to Callers

In some cases, when a time interval component in the string to be parsed contains more than seven digits, parsing operations that succeed in the .NET Framework 3.5 and earlier versions may fail and throw an OverflowException in the .NET Framework 4, The following example illustrates this scenario.

string value = "000000006";
TimeSpan interval;
if (TimeSpan.TryParse(value, out interval))
   Console.WriteLine("{0} --> {1}", value, interval);
else
   Console.WriteLine("Unable to parse '{0}'", value);
// Output from .NET Framework 3.5 and earlier versions: 
//       000000006 --> 6.00:00:00 
// Output from .NET Framework 4: 
//       Unable to parse //000000006//

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.

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

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft