TimeSpan.TryParse Method (String, TimeSpan%)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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)

Syntax

'Declaration
Public Shared Function TryParse ( _
    s As String, _
    <OutAttribute> ByRef result As TimeSpan _
) As Boolean
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 nulla null reference (Nothing in Visual Basic) 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.

Remarks

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 first tries to parse s by using the invariant format. If this is not successful, it next tries each of the culture-specific formats for the current culture.

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.

Module Example
   Sub ParseTimeSpan(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal intervalStr As String)
      ' Write the first part of the output line.
      outputBlock.Text += String.Format("{0,20}   ", intervalStr)

      ' Parse the parameter, and then convert it back to a string.
      Dim intervalVal As TimeSpan
      If TimeSpan.TryParse(intervalStr, intervalVal) Then
         Dim intervalToStr As String = intervalVal.ToString()

         ' Pad the end of the TimeSpan string with spaces if it 
         ' does not contain milliseconds.
         Dim pIndex As Integer = intervalToStr.IndexOf(":"c)
         pIndex = intervalToStr.IndexOf("."c, pIndex)
         If pIndex < 0 Then intervalToStr &= "        "

         outputBlock.Text += String.Format("{0,21}", intervalToStr) & vbCrLf
      ' Handle failure of Example method.
      Else
         outputBlock.Text &= "Parse operation failed." & vbCrLf
      End If
   End Sub

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      outputBlock.Text += String.Format("{0,20}   {1,21}", _
          "String to Parse", "TimeSpan") & vbCrLf
      outputBlock.Text += String.Format("{0,20}   {1,21}", _
          "---------------", "---------------------") & vbCrLf

      ParseTimeSpan(outputBlock, "0")
      ParseTimeSpan(outputBlock, "14")
      ParseTimeSpan(outputBlock, "1:2:3")
      ParseTimeSpan(outputBlock, "0:0:0.250")
      ParseTimeSpan(outputBlock, "10.20:30:40.50")
      ParseTimeSpan(outputBlock, "99.23:59:59.9999999")
      ParseTimeSpan(outputBlock, "0023:0059:0059.0099")
      ParseTimeSpan(outputBlock, "23:0:0")
      ParseTimeSpan(outputBlock, "24:0:0")
      ParseTimeSpan(outputBlock, "0:59:0")
      ParseTimeSpan(outputBlock, "0:60:0")
      ParseTimeSpan(outputBlock, "0:0:59")
      ParseTimeSpan(outputBlock, "0:0:60")
      ParseTimeSpan(outputBlock, "10:")
      ParseTimeSpan(outputBlock, "10:0")
      ParseTimeSpan(outputBlock, ":10")
      ParseTimeSpan(outputBlock, "0:10")
      ParseTimeSpan(outputBlock, "10:20:")
      ParseTimeSpan(outputBlock, "10:20:0")
      ParseTimeSpan(outputBlock, ".123")
      ParseTimeSpan(outputBlock, "0.12:00")
      ParseTimeSpan(outputBlock, "10.")
      ParseTimeSpan(outputBlock, "10.12")
      ParseTimeSpan(outputBlock, "10.12:00")
   End Sub
End Module
' This example generates the following output:
'            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
using System;

public class Example
{
   private static void ParseTimeSpan(System.Windows.Controls.TextBlock outputBlock, string intervalStr)
   {
      // Write the first part of the output line.
      outputBlock.Text += String.Format("{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 += "        ";

         outputBlock.Text += String.Format("{0,21}", intervalToStr) + "\n";
      }
      // Handle failure of TryParse method.
      else
      {
         outputBlock.Text += "Parse operation failed." + "\n";
      }
   }

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.Text += String.Format("{0,20}   {1,21}",
          "String to Parse", "TimeSpan") + "\n";
      outputBlock.Text += String.Format("{0,20}   {1,21}",
          "---------------", "---------------------") + "\n";

      ParseTimeSpan(outputBlock, "0");
      ParseTimeSpan(outputBlock, "14");
      ParseTimeSpan(outputBlock, "1:2:3");
      ParseTimeSpan(outputBlock, "0:0:0.250");
      ParseTimeSpan(outputBlock, "10.20:30:40.50");
      ParseTimeSpan(outputBlock, "99.23:59:59.9999999");
      ParseTimeSpan(outputBlock, "0023:0059:0059.0099");
      ParseTimeSpan(outputBlock, "23:0:0");
      ParseTimeSpan(outputBlock, "24:0:0");
      ParseTimeSpan(outputBlock, "0:59:0");
      ParseTimeSpan(outputBlock, "0:60:0");
      ParseTimeSpan(outputBlock, "0:0:59");
      ParseTimeSpan(outputBlock, "0:0:60");
      ParseTimeSpan(outputBlock, "10:");
      ParseTimeSpan(outputBlock, "10:0");
      ParseTimeSpan(outputBlock, ":10");
      ParseTimeSpan(outputBlock, "0:10");
      ParseTimeSpan(outputBlock, "10:20:");
      ParseTimeSpan(outputBlock, "10:20:0");
      ParseTimeSpan(outputBlock, ".123");
      ParseTimeSpan(outputBlock, "0.12:00");
      ParseTimeSpan(outputBlock, "10.");
      ParseTimeSpan(outputBlock, "10.12");
      ParseTimeSpan(outputBlock, "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

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.