TimeSpan.Parse 方法

定義

將時間間隔的字串表示,轉換成與其相等的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent.

多載

Parse(String)

將時間間隔的字串表示,轉換成與其相等的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider)

使用指定的特定文化特性格式資訊,將時間間隔的範圍表示轉換為其對等的 TimeSpanConverts the span representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

Parse(String, IFormatProvider)

使用指定的特定文化特性格式資訊,將時間間隔的字串表示轉換為其相等的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

Parse(String)

將時間間隔的字串表示,轉換成與其相等的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent.

public:
 static TimeSpan Parse(System::String ^ s);
public static TimeSpan Parse (string s);
static member Parse : string -> TimeSpan
Public Shared Function Parse (s As String) As TimeSpan

參數

s
String

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

傳回

TimeSpan

時間間隔,對應至 sA time interval that corresponds to s.

例外狀況

snulls is null.

s 具有無效的格式。s has an invalid format.

s 代表小於 MinValue 或大於 MaxValue 的數字。s represents a number that is less than MinValue or greater than MaxValue.

-或--or- 天數、小時、分鐘或秒鐘元件中,至少有一個元件超出有效範圍。At least one of the days, hours, minutes, or seconds components is outside its valid range.

範例

下列範例會使用 Parse 方法,將字串陣列中的每個元素轉換成 TimeSpan 值。The following example uses the Parse method to convert each element in a string array to a TimeSpan value. 它會將目前的系統文化特性變更為克羅地亞-克羅地亞 ( "hr-HR" ) 和英文-美國 ( "en-us" ) 說明目前的系統文化特性如何影響剖析作業。It changes the current system culture to Croatian - Croatia ("hr-HR") and English - United States ("en-US") to illustrate how the current system culture affects the parsing operation.

using System;
using System.Globalization;
using System.Threading;

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" };
      string[] cultureNames = { "hr-HR", "en-US"};
      
      // Change the current culture.
      foreach (string cultureName in cultureNames)
      {
         Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
         Console.WriteLine("Current Culture: {0}", 
                           Thread.CurrentThread.CurrentCulture.Name);
         foreach (string value in values)
         {
            try {
               TimeSpan ts = TimeSpan.Parse(value);
               Console.WriteLine("{0} --> {1}", value, ts.ToString("c"));
            }
            catch (FormatException) {
               Console.WriteLine("{0}: Bad Format", value);
            }   
            catch (OverflowException) {
               Console.WriteLine("{0}: Overflow", value);
            }
         } 
         Console.WriteLine();                                
      }
   }
}
// The example displays the following output:
//    Current Culture: hr-HR
//    6 --> 6.00:00:00
//    6:12 --> 06:12:00
//    6: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.3448: Bad Format
//    6:12:14:45,3448 --> 6.12:14:45.3448000
//    6:34:14:45: Overflow
//    
//    Current Culture: en-US
//    6 --> 6.00:00:00
//    6:12 --> 06:12:00
//    6: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.3448 --> 6.12:14:45.3448000
//    6:12:14:45,3448: Bad Format
//    6:34:14:45: Overflow
Imports System.Globalization
Imports System.Threading

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 cultureNames() As String = { "hr-HR", "en-US"}
      
      ' Change the current culture.
      For Each cultureName As String In cultureNames
         Thread.CurrentThread.CurrentCulture = New CultureInfo(cultureName)
         Console.WriteLine("Current Culture: {0}", 
                           Thread.CurrentThread.CurrentCulture.Name)
         For Each value As String In values
            Try
               Dim ts As TimeSpan = TimeSpan.Parse(value)
               Console.WriteLine("{0} --> {1}", value, ts.ToString("c"))
            Catch e As FormatException
               Console.WriteLine("{0}: Bad Format", value)
            Catch e As OverflowException
               Console.WriteLine("{0}: Overflow", value)
            End Try      
         Next 
         Console.WriteLine()                                
      Next
   End Sub
End Module
' The example displays the following output:
'       Current Culture: hr-HR
'       6 --> 6.00:00:00
'       6:12 --> 06:12:00
'       6: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.3448: Bad Format
'       6:12:14:45,3448 --> 6.12:14:45.3448000
'       6:34:14:45: Overflow
'       
'       Current Culture: en-US
'       6 --> 6.00:00:00
'       6:12 --> 06:12:00
'       6: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.3448 --> 6.12:14:45.3448000
'       6:12:14:45,3448: Bad Format
'       6:34:14:45: Overflow

備註

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

[ws][-]{ d | [d.]hhmm[:ss[.ff]]} [ws][ws][-]{ d | [d.]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 引數不是日期值,則必須包含小時和分鐘的元件,其他元件則為選擇性。If the s argument is not a day value only, it must include an hours and a minutes component; other components are optional. 如果存在,則每個時間元件的值必須落在指定的範圍內。If they are present, the values of each time component must fall within a specified range. 例如, hh,hours 元件的值必須介於0到23之間。For example, the value of hh, the hours component, must be between 0 and 23. 因此,將 "23:00:00" 傳遞給方法會傳回 Parse 23 小時的時間間隔。Because of this, passing "23:00:00" to the Parse method returns a time interval of 23 hours. 另一方面,傳遞 "24:00:00" 會傳回24天的時間間隔。On the other hand, passing "24:00:00" returns a time interval of 24 days. 因為 "24" 超出時陣列件的範圍,所以會將其視為天陣列件。Because "24" is outside the range of the hours component, it is interpreted as the days component.

的元件 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 和較早版本中的剖析作業可能會與 .NET Framework 4 和更新版本中的剖析作業有不同的行為。When a time interval component in the string to be parsed contains more than seven digits, parsing operations in the .NET Framework 3.5 and earlier versions may behave differently from parsing operations in the .NET Framework 4 and later versions. 在某些情況下,在 .NET Framework 3.5 及更早版本中成功的剖析作業可能會失敗,並 OverflowException 在 .NET Framework 4 和更新版本中擲回。In some cases, 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. 在其他情況下,在 FormatException .NET Framework 3.5 和較早版本中擲回的作業可能會失敗,並 OverflowException 在 .NET Framework 4 和更新版本中擲回。In other cases, parsing operations that throw a FormatException in the .NET Framework 3.5 and earlier versions may fail and throw an OverflowException in the .NET Framework 4 and later. 下列範例說明這兩種案例。The following example illustrates both scenarios.

string[] values = { "000000006", "12.12:12:12.12345678" };
foreach (string value in values)
{
   try {
      TimeSpan interval = TimeSpan.Parse(value);
      Console.WriteLine("{0} --> {1}", value, interval);
   }   
   catch (FormatException) {
      Console.WriteLine("{0}: Bad Format", value);
   }   
   catch (OverflowException) {
      Console.WriteLine("{0}: Overflow", value);
   }
}

// Output from .NET Framework 3.5 and earlier versions:
//       000000006 --> 6.00:00:00
//       12.12:12:12.12345678: Bad Format      
// Output from .NET Framework 4 and later versions or .NET Core:
//       000000006: Overflow
//       12.12:12:12.12345678: Overflow
Dim values() As String = { "000000006", "12.12:12:12.12345678" }
For Each value As String In values
   Try
      Dim interval As TimeSpan = TimeSpan.Parse(value)
      Console.WriteLine("{0} --> {1}", value, interval)
   Catch e As FormatException
      Console.WriteLine("{0}: Bad Format", value)
   Catch e As OverflowException
      Console.WriteLine("{0}: Overflow", value)
   End Try         
Next
' Output from .NET Framework 3.5 and earlier versions:
'       000000006 --> 6.00:00:00
'       12.12:12:12.12345678: Bad Format      
' Output from .NET Framework 4:
'       000000006: Overflow
'       12.12:12:12.12345678: Overflow

適用於

Parse(ReadOnlySpan<Char>, IFormatProvider)

使用指定的特定文化特性格式資訊,將時間間隔的範圍表示轉換為其對等的 TimeSpanConverts the span representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

public static TimeSpan Parse (ReadOnlySpan<char> input, IFormatProvider? formatProvider = default);
public static TimeSpan Parse (ReadOnlySpan<char> input, IFormatProvider formatProvider = default);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> TimeSpan
Public Shared Function Parse (input As ReadOnlySpan(Of Char), Optional formatProvider As IFormatProvider = Nothing) As TimeSpan

參數

input
ReadOnlySpan<Char>

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

formatProvider
IFormatProvider

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

傳回

TimeSpan

時間間隔,對應至 input,如 formatProvider 所指定。A time interval that corresponds to input, as specified by formatProvider.

適用於

Parse(String, IFormatProvider)

使用指定的特定文化特性格式資訊,將時間間隔的字串表示轉換為其相等的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

public:
 static TimeSpan Parse(System::String ^ input, IFormatProvider ^ formatProvider);
public static TimeSpan Parse (string input, IFormatProvider formatProvider);
public static TimeSpan Parse (string input, IFormatProvider? formatProvider);
static member Parse : string * IFormatProvider -> TimeSpan
Public Shared Function Parse (input As String, formatProvider As IFormatProvider) As TimeSpan

參數

input
String

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

formatProvider
IFormatProvider

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

傳回

TimeSpan

時間間隔,對應至 input,如 formatProvider 所指定。A time interval that corresponds to input, as specified by formatProvider.

例外狀況

inputnullinput is null.

input 具有無效的格式。input has an invalid format.

input 代表小於 MinValue 或大於 MaxValue 的數字。input represents a number that is less than MinValue or greater than MaxValue.

-或--or- input 中的天數、小時、分鐘或秒鐘元件中,至少有一個元件超出有效範圍。At least one of the days, hours, minutes, or seconds components in input is outside its valid range.

範例

下列範例會定義物件的陣列 CultureInfo ,並使用方法呼叫中的每個物件 Parse(String, IFormatProvider) 來剖析字串陣列中的元素。The following example defines an array of CultureInfo objects, and uses each object in calls to the Parse(String, IFormatProvider) 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;
using System.Text.RegularExpressions;

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)
         {
            try {
               TimeSpan ts = TimeSpan.Parse(value, culture);
               Console.Write("{0,20}", ts.ToString("c"));
            }
            catch (FormatException) {
               Console.Write("{0,20}", "Bad Format");
            }   
            catch (OverflowException) {
               Console.Write("{0,20}", "Overflow");
            }      
         }
         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          Bad Format  6.12:14:45.3448000
//    6:12:14:45,3448            Bad Format  6.12:14:45.3448000          Bad Format
//    6:34:14:45                   Overflow            Overflow            Overflow
Imports System.Globalization
Imports System.Threading

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
            Try
               Dim ts As TimeSpan = TimeSpan.Parse(value, culture)
               Console.Write("{0,20}", ts.ToString("c"))
            Catch e As FormatException
               Console.Write("{0,20}", "Bad Format")
            Catch e As OverflowException
               Console.Write("{0,20}", "Overflow")
            End Try      
         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          Bad Format  6.12:14:45.3448000
'    6:12:14:45,3448            Bad Format  6.12:14:45.3448000          Bad Format
'    6:34:14:45                   Overflow            Overflow            Overflow

備註

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

[ws][-]{ d | [d.]hhmm[:ss[.ff]]} [ws][ws][-]{ d | [d.]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 default value is a period (".") character.
hhhh 小時,範圍介於0到23之間。Hours, ranging from 0 to 23.
:: 區分文化特性的時間分隔符號。The culture-sensitive time separator symbol.
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 default value is a period (".") character.
Ffff 選用的小數秒數,由1到7個小數位數所組成。Optional fractional seconds, consisting of one to seven decimal digits.

如果 input 引數不是日期值,則必須包含小時和分鐘的元件,其他元件則為選擇性。If the input argument is not a day value only, it must include an hours and a minutes component; other components are optional. 如果存在,則每個時間元件的值必須落在指定的範圍內。If they are present, the values of each time component must fall within a specified range. 例如, hh,hours 元件的值必須介於0到23之間。For example, the value of hh, the hours component, must be between 0 and 23. 因此,將 "23:00:00" 傳遞給方法會傳回 Parse 23 小時的時間間隔。Because of this, passing "23:00:00" to the Parse method returns a time interval of 23 hours. 另一方面,傳遞 "24:00:00" 會傳回24天的時間間隔。On the other hand, passing "24:00:00" returns a time interval of 24 days. 因為 "24" 超出時陣列件的範圍,所以會將其視為天陣列件。Because "24" is outside the range of the hours component, it is interpreted as the days component.

的元件 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.

Parse(String)方法會嘗試 input 針對所指定的文化特性,使用每個特定文化特性格式來剖析 formatProviderThe Parse(String) 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 和較早版本中的剖析作業可能會與 .NET Framework 4 和更新版本中的剖析作業有不同的行為。When a time interval component in the string to be parsed contains more than seven digits, parsing operations in the .NET Framework 3.5 and earlier versions may behave differently from parsing operations in the .NET Framework 4 and later versions. 在某些情況下,在 .NET Framework 3.5 及更早版本中成功的剖析作業可能會失敗,並 OverflowException 在 .NET Framework 4 和更新版本中擲回。In some cases, 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. 在其他情況下,在 FormatException .NET Framework 3.5 和較早版本中擲回的作業可能會失敗,並 OverflowException 在 .NET Framework 4 和更新版本中擲回。In other cases, parsing operations that throw a FormatException in the .NET Framework 3.5 and earlier versions may fail and throw an OverflowException in the .NET Framework 4 and later. 下列範例說明這兩種案例。The following example illustrates both scenarios.

string[] values = { "000000006", "12.12:12:12.12345678" };
foreach (string value in values)
{
   try {
      TimeSpan interval = TimeSpan.Parse(value);
      Console.WriteLine("{0} --> {1}", value, interval);
   }   
   catch (FormatException) {
      Console.WriteLine("{0}: Bad Format", value);
   }   
   catch (OverflowException) {
      Console.WriteLine("{0}: Overflow", value);
   }
}

// Output from .NET Framework 3.5 and earlier versions:
//       000000006 --> 6.00:00:00
//       12.12:12:12.12345678: Bad Format      
// Output from .NET Framework 4 and later versions or .NET Core:
//       000000006: Overflow
//       12.12:12:12.12345678: Overflow
Dim values() As String = { "000000006", "12.12:12:12.12345678" }
For Each value As String In values
   Try
      Dim interval As TimeSpan = TimeSpan.Parse(value)
      Console.WriteLine("{0} --> {1}", value, interval)
   Catch e As FormatException
      Console.WriteLine("{0}: Bad Format", value)
   Catch e As OverflowException
      Console.WriteLine("{0}: Overflow", value)
   End Try         
Next
' Output from .NET Framework 3.5 and earlier versions:
'       000000006 --> 6.00:00:00
'       12.12:12:12.12345678: Bad Format      
' Output from .NET Framework 4:
'       000000006: Overflow
'       12.12:12:12.12345678: Overflow

適用於