共用方式為


TimeSpan.Parse Method (String)

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

Converts the string representation of a time interval to its TimeSpan equivalent.

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

Syntax

'Declaration
Public Shared Function Parse ( _
    s As String _
) As TimeSpan
public static TimeSpan Parse(
    string s
)

Parameters

  • s
    Type: System.String
    A string that specifies that specifies the time interval to convert.

Return Value

Type: System.TimeSpan
A time interval that corresponds to s.

Exceptions

Exception Condition
ArgumentNullException

s is nulla null reference (Nothing in Visual Basic).

FormatException

s has an invalid format.

OverflowException

s represents a number less than TimeSpan.MinValue or greater than TimeSpan.MaxValue.

-or-

At least one of the days, hours, minutes, or seconds components is outside its valid range.

Remarks

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

[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

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 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 Parse method to create TimeSpan objects from valid TimeSpan strings and to raise exceptions from invalid TimeSpan strings.

' Example of the TimeSpan.Parse( String ) and TimeSpan.ToString( ) 
' methods.

Module Example

   Sub ParseNDisplayTimeSpan(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.
      Try
         Dim intervalVal As TimeSpan = TimeSpan.Parse(intervalStr)
         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

         ' If Parse throws an exception, write the message.
      Catch ex As Exception
         outputBlock.Text &= ex.Message & vbCrLf
      End Try
   End Sub

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      outputBlock.Text += _
          "This example of TimeSpan.Parse( String ) and " & _
          vbCrLf & "TimeSpan.ToString( ) " & _
          "generates the following output." & vbCrLf + vbCrLf
      outputBlock.Text += String.Format("{0,20}   {1,21}", _
          "String to Parse", "TimeSpan or Exception") + vbCrLf
      outputBlock.Text += String.Format("{0,20}   {1,21}", _
          "---------------", "---------------------") + vbCrLf

      ParseNDisplayTimeSpan(outputBlock, "0")
      ParseNDisplayTimeSpan(outputBlock, "14")
      ParseNDisplayTimeSpan(outputBlock, "1:2:3")
      ParseNDisplayTimeSpan(outputBlock, "0:0:0.250")
      ParseNDisplayTimeSpan(outputBlock, "10.20:30:40.50")
      ParseNDisplayTimeSpan(outputBlock, "99.23:59:59.9999999")
      ParseNDisplayTimeSpan(outputBlock, "0023:0059:0059.0099")
      ParseNDisplayTimeSpan(outputBlock, "24:0:0")
      ParseNDisplayTimeSpan(outputBlock, "0:60:0")
      ParseNDisplayTimeSpan(outputBlock, "0:0:60")
      ParseNDisplayTimeSpan(outputBlock, "10:")
      ParseNDisplayTimeSpan(outputBlock, ":10")
      ParseNDisplayTimeSpan(outputBlock, "10:20:")
      ParseNDisplayTimeSpan(outputBlock, ".123")
      ParseNDisplayTimeSpan(outputBlock, "10.")
      ParseNDisplayTimeSpan(outputBlock, "10.12")
   End Sub
End Module

' This example of TimeSpan.Parse( String ) and
' TimeSpan.ToString( ) generates the following output.
' 
'      String to Parse   TimeSpan or Exception
'      ---------------   ---------------------
'                    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
'               24:0:0   TimeSpan overflowed because the duration is too long.
'               0:60:0   TimeSpan overflowed because the duration is too long.
'               0:0:60   TimeSpan overflowed because the duration is too long.
'                  10:   Input string was not in a correct format.
'                  :10   Input string was not in a correct format.
'               10:20:   Input string was not in a correct format.
'                 .123   Input string was not in a correct format.
'                  10.   Input string was not in a correct format.
'                10.12   Input string was not in a correct format.
// Example of the TimeSpan.Parse( string ) and TimeSpan.ToString( ) 
// methods.
using System;

class Example
{
   static void ParseNDisplayTimeSpan(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.
      try
      {
         TimeSpan intervalVal = TimeSpan.Parse(intervalStr);
         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";
      }
      catch (Exception ex)
      {
         // If Parse throws an exception, write the message.
         outputBlock.Text += ex.Message + "\n";
      }
   }

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.Text += 
          "This example of TimeSpan.Parse( string ) and \n" +
          "TimeSpan.ToString( ) " +
          "generates the following output.\n\n";
      outputBlock.Text += String.Format("{0,20}   {1,21}\n",
          "String to Parse", "TimeSpan or Exception");
      outputBlock.Text += String.Format("{0,20}   {1,21}\n",
          "---------------", "---------------------");

      ParseNDisplayTimeSpan(outputBlock, "0");
      ParseNDisplayTimeSpan(outputBlock, "14");
      ParseNDisplayTimeSpan(outputBlock, "1:2:3");
      ParseNDisplayTimeSpan(outputBlock, "0:0:0.250");
      ParseNDisplayTimeSpan(outputBlock, "10.20:30:40.50");
      ParseNDisplayTimeSpan(outputBlock, "99.23:59:59.9999999");
      ParseNDisplayTimeSpan(outputBlock, "0023:0059:0059.0099");
      ParseNDisplayTimeSpan(outputBlock, "24:0:0");
      ParseNDisplayTimeSpan(outputBlock, "0:60:0");
      ParseNDisplayTimeSpan(outputBlock, "0:0:60");
      ParseNDisplayTimeSpan(outputBlock, "10:");
      ParseNDisplayTimeSpan(outputBlock, ":10");
      ParseNDisplayTimeSpan(outputBlock, "10:20:");
      ParseNDisplayTimeSpan(outputBlock, ".123");
      ParseNDisplayTimeSpan(outputBlock, "10.");
      ParseNDisplayTimeSpan(outputBlock, "10.12");
   }
}

/*
This example of TimeSpan.Parse( string ) and
TimeSpan.ToString( ) generates the following output.

     String to Parse   TimeSpan or Exception
     ---------------   ---------------------
                   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
              24:0:0   TimeSpan overflowed because the duration is too long.
              0:60:0   TimeSpan overflowed because the duration is too long.
              0:0:60   TimeSpan overflowed because the duration is too long.
                 10:   Input string was not in a correct format.
                 :10   Input string was not in a correct format.
              10:20:   Input string was not in a correct format.
                .123   Input string was not in a correct format.
                 10.   Input string was not in a correct format.
               10.12   Input string was not in a correct format.
*/

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.