TimeSpan.Parse TimeSpan.Parse TimeSpan.Parse TimeSpan.Parse Method

定义

将时间间隔的字符串表示形式转换为等效的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent.

重载

Parse(String) Parse(String) Parse(String) Parse(String)

将时间间隔的字符串表示形式转换为等效的 TimeSpanConverts the string representation of a time interval to its TimeSpan equivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider)
Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) 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) Parse(String) Parse(String) 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 String String String

一个字符串,用于指定进行转换的时间间隔。A string that specifies the time interval to convert.

返回

s 对应的时间间隔。A time interval that corresponds to s.

异常

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") 和英语美国 ("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.]hh:mm[:ss[.ff]] }[ws][ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

方括号 ([ and ]) 中的元素是可选的。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.
- 可选的负号, 指示负TimeSpan号。An 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, 小时部分的值必须介于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.MaxValue小于或等于的时间间隔。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.

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

当要分析的字符串中的时间间隔组件包含的位数超过7个时, .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. 在其他情况下, 在 .NET Framework 3.5 及FormatException更早版本中引发的分析操作可能会失败, 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:
//       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) Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider)

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

参数

返回

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) 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);
static member Parse : string * IFormatProvider -> TimeSpan
Public Shared Function Parse (input As String, formatProvider As IFormatProvider) As TimeSpan

参数

input
String String String String

一个字符串,用于指定进行转换的时间间隔。A string that specifies the time interval to convert.

formatProvider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个提供区域性特定的格式设置信息的对象。An object that supplies culture-specific formatting information.

返回

input 对应的时间间隔,由 formatProvider 指定。A time interval that corresponds to input, as specified by formatProvider.

异常

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.]hh:mm[: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.
- 可选的负号, 指示负TimeSpan号。An 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, 小时部分的值必须介于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.MaxValue小于或等于的时间间隔。The 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 formatProvider的区域性的每个特定于区域性的格式来进行分析。The Parse(String) method tries to parse input by using each of the culture-specific formats for the culture specified by formatProvider.

参数是一个IFormatProvider实现, 提供有关返回的字符串格式的区域性特定信息。 formatProviderThe 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

当要分析的字符串中的时间间隔组件包含的位数超过7个时, .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. 在其他情况下, 在 .NET Framework 3.5 及FormatException更早版本中引发的分析操作可能会失败, 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:
//       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

适用于