Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Método TimeSpan.Parse (String)

 

Converte a representação da cadeia de caracteres de um intervalo de tempo em seu equivalente TimeSpan.

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

public static TimeSpan Parse(
	string s
)

Parâmetros

s
Type: System.String

Uma cadeia de caracteres que especifica o intervalo de tempo a ser convertido.

Valor Retornado

Type: System.TimeSpan

Um intervalo de tempo que corresponde a s.

Exception Condition
ArgumentNullException

s é null.

FormatException

s tem um formato inválido.

OverflowException

s representa um número que é menor que TimeSpan.MinValue ou maior que TimeSpan.MaxValue.

-ou-

Pelo menos um dos componentes de dias, horas, minutos ou segundos está fora do intervalo válido.

The s parameter contains a time interval specification in 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 T:System.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 that is greater than or equal to F:System.TimeSpan.MinValue and less than or equal to F:System.TimeSpan.MaxValue.

The M:System.TimeSpan.Parse(System.String) method tries to parse s by using each of the culture-specific formats for the current culture.

Observações para os Autores de Chamada:

When a time interval component in the string to be parsed contains more than seven digits, parsing operations in the net_v35_short and earlier versions may behave differently from parsing operations in the net_v40_short. In some cases, parsing operations that succeed in the net_v35_short and earlier versions may fail and throw an T:System.OverflowException in the net_v40_short. In other cases, parsing operations that throw a T:System.FormatException in the net_v35_short and earlier versions may fail and throw an T:System.OverflowException in the net_v40_short. 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

The following example uses the M:System.TimeSpan.Parse(System.String) method to convert each element in a string array to a T:System.TimeSpan value. 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

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1
Retornar ao início
Mostrar: