TimeSpan.TryParse 方法

定義

將指定的時間間隔字串表示,轉換為其相等的 TimeSpan,並傳回一個值表示轉換是否成功。Converts the specified 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)

使用指定的特定文件特性格式資訊,將時間間隔的範圍表示轉換為其對等的 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)

將時間間隔的範圍表示轉換為其對等的 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, TimeSpan)

將時間間隔的字串表示,轉換為其相等的 TimeSpan,並傳回一個值表示轉換是否成功。Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, TimeSpan)

使用指定的特定文件特性格式資訊,將時間間隔的字串表示轉換為其相等的 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(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

使用指定的特定文件特性格式資訊,將時間間隔的範圍表示轉換為其對等的 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.

public:
 static bool TryParse(ReadOnlySpan<char> input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParse (ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParse (input As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

參數

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

這個方法在傳回時會包含 input 所指定的時間間隔之物件;如果轉換失敗,則為 ZeroWhen 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.

傳回

Boolean

如果 input 轉換成功,則為 true,否則為 falsetrue if input was converted successfully; otherwise, false. 如果 input 參數是 nullEmpty、具有無效格式、代表小於 MinValue 或大於 MaxValue 的時間間隔,或是其天數、時數、分鐘數或秒數項目至少有一個超出有效範圍,這項作業就會傳回 falseThis operation returns false if the input parameter is null or Empty, has an invalid format, represents a time interval that is less than MinValue or greater than MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

適用於

TryParse(ReadOnlySpan<Char>, TimeSpan)

將時間間隔的範圍表示轉換為其對等的 TimeSpan,並傳回值以指出轉換是否成功。Converts the span representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (ReadOnlySpan<char> s, out TimeSpan result);
static member TryParse : ReadOnlySpan<char> * TimeSpan -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As TimeSpan) As Boolean

參數

s
ReadOnlySpan<Char>

範圍,其包含代表要轉換時間間隔的字元。A span containing the characters representing the time interval to convert.

result
TimeSpan

這個方法在傳回時會包含 s 所指定的時間間隔之物件;如果轉換失敗,則為 ZeroWhen 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.

傳回

Boolean

如果 s 轉換成功,則為 true,否則為 falsetrue if s was converted successfully; otherwise, false. 如果 s 參數是 nullEmpty、具有無效格式、代表小於 MinValue 或大於 MaxValue 的時間間隔,或是其天數、時數、分鐘數或秒數項目至少有一個超出有效範圍,這項作業就會傳回 falseThis operation returns false if the s parameter is null or Empty, has an invalid format, represents a time interval that is less than MinValue or greater than MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

適用於

TryParse(String, TimeSpan)

將時間間隔的字串表示,轉換為其相等的 TimeSpan,並傳回一個值表示轉換是否成功。Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (string s, out TimeSpan result);
public static bool TryParse (string? s, out TimeSpan? result);
static member TryParse : string * TimeSpan -> bool
Public Shared Function TryParse (s As String, ByRef result As TimeSpan) As Boolean

參數

s
String

字串,指定要轉換的時間間隔。A string that specifies the time interval to convert.

result
TimeSpan

這個方法在傳回時會包含 s 所指定的時間間隔之物件;如果轉換失敗,則為 ZeroWhen 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.

傳回

Boolean

如果 s 轉換成功,則為 true,否則為 falsetrue if s was converted successfully; otherwise, false. 如果 s 參數是 nullEmpty、具有無效格式、代表小於 MinValue 或大於 MaxValue 的時間間隔,或是其天數、時數、分鐘數或秒數項目至少有一個超出有效範圍,這項作業就會傳回 falseThis operation returns false if the s parameter is null or Empty, has an invalid format, represents a time interval that is less than MinValue or greater than MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

範例

下列範例 TryParse 會使用方法, TimeSpan 從有效的字串建立物件 TimeSpan ,並指出剖析作業失敗的時間,因為時間範圍字串無效。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
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

備註

TryParse方法與 TimeSpan.Parse(String) 方法類似,不同之處在于它不會在轉換失敗時擲回例外狀況。The TryParse method is like the TimeSpan.Parse(String) method, except that it does not throw an exception if the conversion fails.

s參數包含下列格式的時間間隔規格:The s parameter contains a time interval specification in the form:

[ws][-]{ d | dhhmm[:ss[。ff]] | hhmm[:ss[。ff]] }[ws][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
wsws 選擇性的空白字元。Optional white space.
- 選用的減號,表示負號 TimeSpanAn optional minus sign, which indicates a negative TimeSpan.
dd 天,範圍介於0到10675199之間。Days, ranging from 0 to 10675199.
.. 區分文化特性的符號,可將天數與時數隔開。A culture-sensitive symbol that separates days from hours. 非變異格式會使用句點 ( ".") 字元。The invariant format uses a period (".") character.
hhhh 小時,範圍介於0到23之間。Hours, ranging from 0 to 23.
:: 區分文化特性的時間分隔符號。The culture-sensitive time separator symbol. 不變的格式會使用冒號 ( ":" ) 字元。The invariant format uses a colon (":") character.
mmmm 分鐘,範圍介於0到59之間。Minutes, ranging from 0 to 59.
ssss 選用的秒數,範圍介於0到59之間。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.
Ffff 選用的小數秒數,由1到7個小數位數所組成。Optional fractional seconds, consisting of one to seven decimal digits.

的元件 s 必須共同指定大於或等於 TimeSpan.MinValue 且小於或等於的時間間隔 TimeSpan.MaxValueThe 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.

Parse(String)方法會嘗試 s 使用目前文化特性的每個特定文化特性格式來剖析。The Parse(String) method tries to parse s by using each of the culture-specific formats for the current culture.

呼叫者注意事項Notes to callers

在某些情況下,當要剖析的字串中的時間間隔元件包含七位數以上時,在 .NET Framework 3.5 及更早版本中成功的剖析作業可能會失敗,並 OverflowException 在 .NET Framework 4 和更新版本中擲回。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 and later versions. 下列範例說明此案例。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//
Dim value As String = "000000006"
Dim interval As TimeSpan
If TimeSpan.TryParse(value, interval) Then
   Console.WriteLine("{0} --> {1}", value, interval)
Else
   Console.WriteLine("Unable to parse '{0}'", value)
End If
' Output from .NET Framework 3.5 and earlier versions:
'       000000006 --> 6.00:00:00
' Output from .NET Framework 4:
'       Unable to parse '000000006'

適用於

TryParse(String, IFormatProvider, TimeSpan)

使用指定的特定文件特性格式資訊,將時間間隔的字串表示轉換為其相等的 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.

public:
 static bool TryParse(System::String ^ input, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParse (string input, IFormatProvider formatProvider, out TimeSpan result);
public static bool TryParse (string? input, IFormatProvider? formatProvider, out TimeSpan? result);
static member TryParse : string * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParse (input As String, formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

參數

input
String

字串,指定要轉換的時間間隔。A string that specifies the time interval to convert.

formatProvider
IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

result
TimeSpan

這個方法在傳回時會包含 input 所指定的時間間隔之物件;如果轉換失敗,則為 ZeroWhen 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.

傳回

Boolean

如果 input 轉換成功,則為 true,否則為 falsetrue if input was converted successfully; otherwise, false. 如果 input 參數是 nullEmpty、具有無效格式、代表小於 MinValue 或大於 MaxValue 的時間間隔,或是其天數、時數、分鐘數或秒數項目至少有一個超出有效範圍,這項作業就會傳回 falseThis operation returns false if the input parameter is null or Empty, has an invalid format, represents a time interval that is less than MinValue or greater than MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

範例

下列範例會定義物件的陣列 CultureInfo ,並使用方法呼叫中的每個物件 TryParse(String, IFormatProvider, TimeSpan) 來剖析字串陣列中的元素。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.

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
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { "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" }
      Dim cultures() As CultureInfo = { New CultureInfo("en-US"), 
                                        New CultureInfo("ru-RU"),
                                        CultureInfo.InvariantCulture }
      
      Dim header As String = String.Format("{0,-17}", "String")
      For Each culture As CultureInfo In cultures
         header += If(culture.Equals(CultureInfo.InvariantCulture), 
                      String.Format("{0,20}", "Invariant"),
                      String.Format("{0,20}", culture.Name))
      Next
      Console.WriteLine(header)
      Console.WriteLine()
      
      For Each value As String In values
         Console.Write("{0,-17}", value)
         For Each culture As CultureInfo In cultures
            Dim interval As New TimeSpan()
            If TimeSpan.TryParse(value, culture, interval) Then
               Console.Write("{0,20}", interval.ToString("c"))
            Else
               Console.Write("{0,20}", "Unable to Parse")
            End If     
         Next
         Console.WriteLine()                                
      Next
   End Sub
End Module
' 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

備註

TryParse(String, IFormatProvider, TimeSpan)方法與 Parse(String, IFormatProvider) 方法類似,不同之處在于它不會在轉換失敗時擲回例外狀況。The TryParse(String, IFormatProvider, TimeSpan) method is like the Parse(String, IFormatProvider) method, except that it does not throw an exception if the conversion fails.

input參數包含下列格式的時間間隔規格:The input parameter contains a time interval specification in the form:

[ws][-]{ d | dhhmm[:ss[。ff]] | hhmm[:ss[。ff]] }[ws][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
wsws 選擇性的空白字元。Optional white space.
- 選用的減號,表示負號 TimeSpanAn optional minus sign, which indicates a negative TimeSpan.
dd 天,範圍介於0到10675199之間。Days, ranging from 0 to 10675199.
.. 區分文化特性的符號,可將天數與時數隔開。A culture-sensitive symbol that separates days from hours. 非變異格式會使用句點 ( ".") 字元。The invariant format uses a period (".") character.
hhhh 小時,範圍介於0到23之間。Hours, ranging from 0 to 23.
:: 區分文化特性的時間分隔符號。The culture-sensitive time separator symbol. 不變的格式會使用冒號 ( ":" ) 字元。The invariant format uses a colon (":") character.
mmmm 分鐘,範圍介於0到59之間。Minutes, ranging from 0 to 59.
ssss 選用的秒數,範圍介於0到59之間。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.
Ffff 選用的小數秒數,由1到7個小數位數所組成。Optional fractional seconds, consisting of one to seven decimal digits.

的元件 input 必須共同指定大於或等於 TimeSpan.MinValue 且小於或等於的時間間隔 TimeSpan.MaxValueThe components of input must collectively specify a time interval that is greater than or equal to TimeSpan.MinValue and less than or equal to TimeSpan.MaxValue.

TryParse(String, IFormatProvider, TimeSpan)方法會嘗試 input 針對所指定的文化特性,使用每個特定文化特性格式來剖析 formatProviderThe TryParse(String, IFormatProvider, TimeSpan) method tries to parse input by using each of the culture-specific formats for the culture specified by formatProvider.

formatProvider參數是一個 IFormatProvider 執行,可提供有關所傳回字串格式的特定文化特性資訊。The formatProvider parameter is an IFormatProvider implementation that provides culture-specific information about the format of the returned string. formatProvider參數可以是下列任何一項:The formatProvider parameter can be any of the following:

如果 formatProvidernull ,則會 DateTimeFormatInfo 使用與目前文化特性相關聯的物件。If formatProvider is null, the DateTimeFormatInfo object that is associated with the current culture is used.

呼叫者注意事項Notes to callers

在某些情況下,當剖析字串中的時間間隔元件包含七位數以上時,在 .NET Framework 3.5 和更早版本中成功並傳回的剖析作業 可能會失敗,並 在 the.NET Framework 4 和更新版本中傳回,下列範例將說明這種情況。In some cases, when a time interval component in the string to be parsed contains more than seven digits, parsing operations that succeed and return in the .NET Framework 3.5 and earlier versions may fail and return in the.NET Framework 4 and later versions, 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//
Dim value As String = "000000006"
Dim interval As TimeSpan
If TimeSpan.TryParse(value, interval) Then
   Console.WriteLine("{0} --> {1}", value, interval)
Else
   Console.WriteLine("Unable to parse '{0}'", value)
End If
' Output from .NET Framework 3.5 and earlier versions:
'       000000006 --> 6.00:00:00
' Output from .NET Framework 4:
'       Unable to parse '000000006'

適用於