Export (0) Print
Expand All

TimeSpan.TryParse Method

Updated: July 2008

Constructs a new TimeSpan object from a time interval specified in a string. Parameters specify the time interval and the variable where the new TimeSpan object is returned.

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

'Declaration
Public Shared Function TryParse ( _
	s As String, _
	<OutAttribute> ByRef result As TimeSpan _
) As Boolean
'Usage
Dim s As String 
Dim result As TimeSpan 
Dim returnValue As Boolean 

returnValue = TimeSpan.TryParse(s, result)

Parameters

s
Type: System.String

A string that specifies a time interval.

result
Type: System.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.

Return Value

Type: System.Boolean
true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is Nothing, has an invalid format, represents a time interval less than MinValue or greater than 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 the TryParse method does not throw an exception if the conversion fails.

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

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

Items in square brackets ([ and ]) are optional. One selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required. Colons and periods (: and .) are literal characters and required. Other items are as follows.

Item

Description

ws

Optional white space.

"-"

Optional minus sign indicating a negative TimeSpan.

d

Days, ranging from 0 to 10675199.

hh

Hours, ranging from 0 to 23.

mm

Minutes, ranging from 0 to 59.

ss

Optional seconds, ranging from 0 to 59.

ff

Optional fractional seconds, consisting of 1 to 7 decimal digits.

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

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 TryParse
    Sub ParseTimeSpan( intervalStr As String )
        ' Write the first part of the output line.
        Console.Write( "{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 &= "        "

            Console.WriteLine( "{0,21}", intervalToStr )
         ' Handle failure of TryParse method. 
         Else
            Console.WriteLine("Parse operation failed.")
        End If 
    End Sub  

    Public Sub 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")
    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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0

Date

History

Reason

July 2008

Added an example.

Customer feedback.

Community Additions

ADD
Show:
© 2014 Microsoft