TimeSpan.ParseExact Método

Definición

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan. El formato de la representación de cadena debe coincidir exactamente con un formato ya especificado.

Sobrecargas

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando el formato y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpanStyles)

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando los formatos y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

ParseExact(String, String[], IFormatProvider, TimeSpanStyles)

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando los formatos y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

ParseExact(String, String[], IFormatProvider)

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando la matriz de cadenas de formato especificadas y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

ParseExact(String, String, IFormatProvider)

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando el formato especificado, así como la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles)

Convierte la representación de carácter de un intervalo de tiempo en su valor TimeSpan equivalente, mediante el formato especificado y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando el formato y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

public:
 static TimeSpan ParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles);
public static TimeSpan ParseExact (string input, string format, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles);
public static TimeSpan ParseExact (string input, string format, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles);
static member ParseExact : string * string * IFormatProvider * System.Globalization.TimeSpanStyles -> TimeSpan
Public Shared Function ParseExact (input As String, format As String, formatProvider As IFormatProvider, styles As TimeSpanStyles) As TimeSpan

Parámetros

input
String

Cadena que especifica el intervalo de tiempo que se va a convertir.

format
String

Cadena de formato estándar o personalizado que define el formato requerido de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

styles
TimeSpanStyles

Combinación bit a bit de valores de enumeración que define los elementos de estilo que pueden estar presentes en input.

Devoluciones

Intervalo de tiempo que corresponde a input, de acuerdo con lo especificado por format, formatProvider y styles.

Excepciones

styles es un valor de TimeSpanStyles no válido.

input es null.

input tiene un formato no válido.

input representa un número menor que TimeSpan.MinValue o mayor que TimeSpan.MaxValue.

o bien

Al menos uno de los componentes de días, horas, minutos o segundos de input está fuera del intervalo válido.

Ejemplos

En el ejemplo siguiente se usa el ParseExact(String, String, IFormatProvider) método para analizar varias representaciones de cadena de intervalos de tiempo mediante varias cadenas de formato y referencias culturales. También usa el TimeSpanStyles.AssumeNegative valor para interpretar cada cadena como un intervalo de tiempo negativo. La salida del ejemplo muestra que el TimeSpanStyles.AssumeNegative estilo afecta al valor devuelto solo cuando se usa con cadenas de formato personalizado.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string intervalString, format;
      TimeSpan interval;
      CultureInfo culture = null;
      
      // Parse hour:minute value with custom format specifier.
      intervalString = "17:14";
      format = "h\\:mm";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      }      
      
      // Parse hour:minute:second value with "g" specifier.
      intervalString = "17:14:48";
      format = "g";
      culture = CultureInfo.InvariantCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse hours:minute.second value with custom format specifier.     
      intervalString = "17:14:48.153";
      format = @"h\:mm\:ss\.fff";
      culture = null;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 

      // Parse days:hours:minute.second value with "G" specifier 
      // and current (en-US) culture.     
      intervalString = "3:17:14:48.153";
      format = "G";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
            
      // Parse days:hours:minute.second value with a custom format specifier.     
      intervalString = "3:17:14:48.153";
      format = @"d\:hh\:mm\:ss\.fff";
      culture = null;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse days:hours:minute.second value with "G" specifier 
      // and fr-FR culture.     
      intervalString = "3:17:14:48,153";
      format = "G";
      culture = new CultureInfo("fr-FR");
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 

      // Parse a single number using the "c" standard format string. 
      intervalString = "12";
      format = "c";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        null, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse a single number using the "%h" custom format string. 
      format = "%h";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        null, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse a single number using the "%s" custom format string. 
      format = "%s";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        null, TimeSpanStyles.AssumeNegative);
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
   }
}
// The example displays the following output:
//    '17:14' (h\:mm) --> -17:14:00
//    '17:14:48' (g) --> 17:14:48
//    '17:14:48.153' (h\:mm\:ss\.fff) --> -17:14:48.1530000
//    '3:17:14:48.153' (G) --> 3.17:14:48.1530000
//    '3:17:14:48.153' (d\:hh\:mm\:ss\.fff) --> -3.17:14:48.1530000
//    '3:17:14:48,153' (G) --> 3.17:14:48.1530000
//    '12' (c) --> 12.00:00:00
//    '12' (%h) --> -12:00:00
//    '12' (%s) --> -00:00:12
open System
open System.Globalization

do
    // Parse hour:minute value with custom format specifier.
    let intervalString = "17:14"
    let format = "h\\:mm"
    let culture = CultureInfo.CurrentCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse hour:minute:second value with "g" specifier.
    let intervalString = "17:14:48"
    let format = "g"
    let culture = CultureInfo.InvariantCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse hours:minute.second value with custom format specifier.     
    let intervalString = "17:14:48.153"
    let format = @"h\:mm\:ss\.fff"
    let culture = null
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"

    // Parse days:hours:minute.second value with "G" specifier 
    // and current (en-US) culture.     
    let intervalString = "3:17:14:48.153"
    let format = "G"
    let culture = CultureInfo.CurrentCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
        
    // Parse days:hours:minute.second value with a custom format specifier.     
    let intervalString = "3:17:14:48.153"
    let format = @"d\:hh\:mm\:ss\.fff"
    let culture = null
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse days:hours:minute.second value with "G" specifier 
    // and fr-FR culture.     
    let intervalString = "3:17:14:48,153"
    let format = "G"
    let culture = new CultureInfo("fr-FR")
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"

    // Parse a single number using the "c" standard format string. 
    let intervalString = "12"
    let format = "c"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse a single number using the "%h" custom format string. 
    let format = "%h"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse a single number using the "%s" custom format string. 
    let format = "%s"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative)
        printfn $"'{intervalString}' ({format}) --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
// The example displays the following output:
//    '17:14' (h\:mm) --> -17:14:00
//    '17:14:48' (g) --> 17:14:48
//    '17:14:48.153' (h\:mm\:ss\.fff) --> -17:14:48.1530000
//    '3:17:14:48.153' (G) --> 3.17:14:48.1530000
//    '3:17:14:48.153' (d\:hh\:mm\:ss\.fff) --> -3.17:14:48.1530000
//    '3:17:14:48,153' (G) --> 3.17:14:48.1530000
//    '12' (c) --> 12.00:00:00
//    '12' (%h) --> -12:00:00
//    '12' (%s) --> -00:00:12
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim intervalString, format As String
      Dim interval As TimeSpan
      Dim culture As CultureInfo = Nothing
      
      ' Parse hour:minute value with custom format specifier.
      intervalString = "17:14"
      format = "h\:mm"
      culture = CultureInfo.CurrentCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try      
      
      ' Parse hour:minute:second value with "g" specifier.
      intervalString = "17:14:48"
      format = "g"
      culture = CultureInfo.InvariantCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse hours:minute.second value with custom format specifier.     
      intervalString = "17:14:48.153"
      format = "h\:mm\:ss\.fff"
      culture = Nothing
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 

      ' Parse days:hours:minute.second value with "G" specifier 
      ' and current (en-US) culture.     
      intervalString = "3:17:14:48.153"
      format = "G"
      culture = CultureInfo.CurrentCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
            
      ' Parse days:hours:minute.second value with a custom format specifier.     
      intervalString = "3:17:14:48.153"
      format = "d\:hh\:mm\:ss\.fff"
      culture = Nothing
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse days:hours:minute.second value with "G" specifier 
      ' and fr-FR culture.     
      intervalString = "3:17:14:48,153"
      format = "G"
      culture = New CultureInfo("fr-FR")
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        culture, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 

      ' Parse a single number using the "c" standard format string. 
      intervalString = "12"
      format = "c"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        Nothing, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse a single number using the "%h" custom format string. 
      format = "%h"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        Nothing, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse a single number using the "%s" custom format string. 
      format = "%s"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, 
                                        Nothing, TimeSpanStyles.AssumeNegative)
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
   End Sub
End Module
' The example displays the following output:
'    '17:14' (h\:mm) --> -17:14:00
'    '17:14:48' (g) --> 17:14:48
'    '17:14:48.153' (h\:mm\:ss\.fff) --> -17:14:48.1530000
'    '3:17:14:48.153' (G) --> 3.17:14:48.1530000
'    '3:17:14:48.153' (d\:hh\:mm\:ss\.fff) --> -3.17:14:48.1530000
'    '3:17:14:48,153' (G) --> 3.17:14:48.1530000
'    '12' (c) --> 12.00:00:00
'    '12' (%h) --> -12:00:00
'    '12' (%s) --> -00:00:12

Comentarios

El ParseExact método analiza la representación de cadena de un intervalo de tiempo, que debe estar en el formato definido por el format parámetro, excepto que se omiten los caracteres de espacio en blanco iniciales y finales. Dado que input debe cumplir exactamente el formato de , siempre debe usar el control de excepciones al convertir una entrada de cadena por parte del usuario en un intervalo de format tiempo. Si prefiere no usar el control de excepciones, puede llamar al TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) método en su lugar.

El format parámetro es una cadena que contiene un único especificador de formato estándar o uno o varios especificadores de formato personalizado que definen el formato necesario de input. Para obtener más información sobre las cadenas de formato válidas, vea Cadenas de formato TimeSpan estándar y Cadenas de formato TimeSpan personalizados.

Importante

El ParseExact método usa las convenciones de la referencia cultural especificada por el formatProvider parámetro solo si format es una cadena de formato estándar TimeSpan cuyo valor es "g" o "G". Las cadenas de formato estándar "c", "t" y "T" usan las convenciones de formato de la referencia cultural invariable. Las cadenas de formato personalizado definen el formato preciso de la cadena de entrada y usan caracteres literales para separar los componentes de un intervalo de tiempo.

El formatProvider parámetro es una IFormatProvider implementación que proporciona información específica de la referencia cultural sobre el formato de la cadena devuelta si format es una cadena de formato estándar. El formatProvider parámetro puede ser cualquiera de los siguientes:

Si formatProvider es null, se usa el DateTimeFormatInfo objeto asociado a la referencia cultural actual.

El styles parámetro afecta a la interpretación de las cadenas que se analizan mediante cadenas de formato personalizado. Determina si input se interpreta como un intervalo de tiempo negativo solo si hay un signo negativo (TimeSpanStyles.None) o si siempre se interpreta como un intervalo de tiempo negativo (TimeSpanStyles.AssumeNegative). Si TimeSpanStyles.AssumeNegative no se usa, format debe incluir un símbolo de signo negativo literal (como "\-") para analizar correctamente un intervalo de tiempo negativo.

Consulte también

Se aplica a

ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpanStyles)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando los formatos y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

public static TimeSpan ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None);
public static TimeSpan ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None);
static member ParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.TimeSpanStyles -> TimeSpan
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), formats As String(), formatProvider As IFormatProvider, Optional styles As TimeSpanStyles = System.Globalization.TimeSpanStyles.None) As TimeSpan

Parámetros

input
ReadOnlySpan<Char>

Un intervalo que especifica el intervalo de tiempo que se va a convertir.

formats
String[]

Una matriz de cadenas de formato estándar o personalizado que define el formato necesario de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

styles
TimeSpanStyles

Combinación bit a bit de valores de enumeración que define los elementos de estilo que pueden estar presentes en input.

Devoluciones

Intervalo de tiempo que corresponde a input, de acuerdo con lo especificado por formats, formatProvider y styles.

Se aplica a

ParseExact(String, String[], IFormatProvider, TimeSpanStyles)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando los formatos y los estilos especificados, y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

public:
 static TimeSpan ParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles);
public static TimeSpan ParseExact (string input, string[] formats, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles);
public static TimeSpan ParseExact (string input, string[] formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles);
static member ParseExact : string * string[] * IFormatProvider * System.Globalization.TimeSpanStyles -> TimeSpan
Public Shared Function ParseExact (input As String, formats As String(), formatProvider As IFormatProvider, styles As TimeSpanStyles) As TimeSpan

Parámetros

input
String

Cadena que especifica el intervalo de tiempo que se va a convertir.

formats
String[]

Una matriz de cadenas de formato estándar o personalizado que define el formato necesario de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

styles
TimeSpanStyles

Combinación bit a bit de valores de enumeración que define los elementos de estilo que pueden estar presentes en input.

Devoluciones

Intervalo de tiempo que corresponde a input, de acuerdo con lo especificado por formats, formatProvider y styles.

Excepciones

styles es un valor de TimeSpanStyles no válido.

input es null.

input tiene un formato no válido.

input representa un número menor que TimeSpan.MinValue o mayor que TimeSpan.MaxValue.

o bien

Al menos uno de los componentes de días, horas, minutos o segundos de input está fuera del intervalo válido.

Ejemplos

En el ejemplo siguiente se llama al ParseExact(String, String[], IFormatProvider, TimeSpanStyles) método para convertir cada elemento de una matriz de cadenas en un TimeSpan valor. Las cadenas pueden representar un intervalo de tiempo en el formato corto general o en el formato largo general.

Además, el ejemplo cambia la forma en que los métodos de análisis de intervalo de tiempo interpretan un solo dígito. Normalmente, un solo dígito se interpreta como el número de días en un intervalo de tiempo. En su lugar, la %h cadena de formato personalizado se usa para interpretar un solo dígito como el número de horas. Para que este cambio sea efectivo, tenga en cuenta que la %h cadena de formato personalizado debe preceder a las demás cadenas de formato de la formats matriz. Tenga en cuenta también de la salida que la TimeSpanStyles.AssumeNegative marca especificada en la llamada al método solo se usa al analizar una cadena con este especificador de formato.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] inputs = { "3", "16:42", "1:6:52:35.0625", 
                          "1:6:52:35,0625" }; 
      string[] formats = { "%h", "g", "G" };
      TimeSpan interval;
      CultureInfo culture = new CultureInfo("de-DE");
      
      // Parse each string in inputs using formats and the de-DE culture.
      foreach (string input in inputs) {
         try {
            interval = TimeSpan.ParseExact(input, formats, culture,
                                           TimeSpanStyles.AssumeNegative);
            Console.WriteLine("{0} --> {1:c}", input, interval);
         }
         catch (FormatException) {
            Console.WriteLine("{0} --> Bad Format", input);
         }      
         catch (OverflowException) {
            Console.WriteLine("{0} --> Overflow", input);   
         }            
      }
   }
}
// The example displays the following output:
//       3 --> -03:00:00
//       16:42 --> 16:42:00
//       1:6:52:35.0625 --> Bad Format
//       1:6:52:35,0625 --> 1.06:52:35.0625000
open System
open System.Globalization

let inputs = 
    [| "3"; "16:42"; "1:6:52:35.0625"; "1:6:52:35,0625" |] 
let formats = [| "%h"; "g"; "G" |]
let culture = CultureInfo "de-DE"

// Parse each string in inputs using formats and the de-DE culture.
for input in inputs do
    try
        let interval = 
            TimeSpan.ParseExact(input, formats, culture, TimeSpanStyles.AssumeNegative)
        printfn $"{input} --> {interval:c}"
    with
    | :? FormatException ->
        printfn $"{input} --> Bad Format"
    | :? OverflowException ->
        printfn $"{input} --> Overflow"
// The example displays the following output:
//       3 --> -03:00:00
//       16:42 --> 16:42:00
//       1:6:52:35.0625 --> Bad Format
//       1:6:52:35,0625 --> 1.06:52:35.0625000
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim inputs() As String = { "3", "16:42", "1:6:52:35.0625", 
                                 "1:6:52:35,0625" } 
      Dim formats() As String = { "%h", "g", "G" }
      Dim interval As TimeSpan
      Dim culture As New CultureInfo("de-DE")
      
      ' Parse each string in inputs using formats and the de-DE culture.
      For Each input As String In inputs
         Try
            interval = TimeSpan.ParseExact(input, formats, culture, 
                                           TimeSpanStyles.AssumeNegative)
            Console.WriteLine("{0} --> {1:c}", input, interval)   
         Catch e As FormatException
            Console.WriteLine("{0} --> Bad Format", input)   
         Catch e As OverflowException
            Console.WriteLine("{0} --> Overflow", input)   
         End Try            
      Next
   End Sub
End Module
' The example displays the following output:
'       3 --> -03:00:00
'       16:42 --> 16:42:00
'       1:6:52:35.0625 --> Bad Format
'       1:6:52:35,0625 --> 1.06:52:35.0625000

Comentarios

El ParseExact(String, String[], IFormatProvider, TimeSpanStyles) método analiza la representación de cadena de un intervalo de tiempo, que debe estar en uno de los formatos definidos por el formats parámetro, excepto que se omiten los caracteres de espacio en blanco iniciales y finales. Dado que input debe cumplir exactamente uno de los formatos especificados en formats, siempre debe usar el control de excepciones al convertir una entrada de cadena por parte del usuario en un intervalo de tiempo. Si prefiere no usar el control de excepciones, puede llamar al TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) método en su lugar.

El formats parámetro es una matriz de cadenas cuyos elementos constan de un único especificador de formato estándar, o uno o varios especificadores de formato personalizado que definen el formato necesario de input. Para obtener más información sobre las cadenas de formato válidas, vea Cadenas de formato TimeSpan estándar y Cadenas de formato TimeSpan personalizados. input debe corresponder exactamente a un miembro de formats para que la operación de análisis se realice correctamente. La operación de análisis intenta coincidir input con cada elemento a formats partir del primer elemento de la matriz.

Importante

El ParseExact método usa las convenciones de la referencia cultural especificada por el formatProvider parámetro solo si la cadena de formato utilizada para analizar input es una cadena de formato estándar TimeSpan cuyo valor es "g" o "G". Las cadenas de formato estándar "c", "t" y "T" usan las convenciones de formato de la referencia cultural invariable. Las cadenas de formato personalizado definen el formato preciso de la cadena de entrada y usan caracteres literales para separar los componentes de un intervalo de tiempo.

El formatProvider parámetro es una IFormatProvider implementación que proporciona información específica de la referencia cultural sobre el formato de la cadena devuelta si la cadena de formato utilizada para analizar input es una cadena de formato estándar. El formatProvider parámetro puede ser cualquiera de los siguientes:

Si formatProvider es null, se usa el DateTimeFormatInfo objeto asociado a la referencia cultural actual.

El styles parámetro afecta a la interpretación de las cadenas que se analizan mediante cadenas de formato personalizado. Determina si input se interpreta como un intervalo de tiempo negativo solo si hay un signo negativo (TimeSpanStyles.None) o si siempre se interpreta como un intervalo de tiempo negativo (TimeSpanStyles.AssumeNegative). Si TimeSpanStyles.AssumeNegative no se usa, format debe incluir un símbolo de signo negativo literal (como "\-") para analizar correctamente un intervalo de tiempo negativo.

Consulte también

Se aplica a

ParseExact(String, String[], IFormatProvider)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando la matriz de cadenas de formato especificadas y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados.

public:
 static TimeSpan ParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider);
public static TimeSpan ParseExact (string input, string[] formats, IFormatProvider formatProvider);
public static TimeSpan ParseExact (string input, string[] formats, IFormatProvider? formatProvider);
static member ParseExact : string * string[] * IFormatProvider -> TimeSpan
Public Shared Function ParseExact (input As String, formats As String(), formatProvider As IFormatProvider) As TimeSpan

Parámetros

input
String

Cadena que especifica el intervalo de tiempo que se va a convertir.

formats
String[]

Una matriz de cadenas de formato estándar o personalizado que define el formato necesario de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

Intervalo de tiempo que corresponde a input de acuerdo con lo especificado por formats y formatProvider.

Excepciones

input es null.

input tiene un formato no válido.

input representa un número menor que TimeSpan.MinValue o mayor que TimeSpan.MaxValue.

o bien

Al menos uno de los componentes de días, horas, minutos o segundos de input está fuera del intervalo válido.

Ejemplos

En el ejemplo siguiente se llama al ParseExact(String, String[], IFormatProvider) método para convertir cada elemento de una matriz de cadenas en un TimeSpan valor. En el ejemplo se interpretan las cadenas mediante las convenciones de formato de la referencia cultural Francés - Francia ("fr-FR"). Las cadenas pueden representar un intervalo de tiempo en el formato corto general o en el formato largo general.

Además, el ejemplo cambia la forma en que los métodos de análisis de intervalo de tiempo interpretan un solo dígito. Normalmente, un solo dígito se interpreta como el número de días en un intervalo de tiempo. En su lugar, la %h cadena de formato personalizado se usa para interpretar un solo dígito como el número de horas. Para que este cambio sea efectivo, tenga en cuenta que la %h cadena de formato personalizado debe preceder a las demás cadenas de formato de la formats matriz.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] inputs = { "3", "16:42", "1:6:52:35.0625", 
                          "1:6:52:35,0625" }; 
      string[] formats = { "g", "G", "%h"};
      TimeSpan interval;
      CultureInfo culture = new CultureInfo("fr-FR");
      
      // Parse each string in inputs using formats and the fr-FR culture.
      foreach (string input in inputs) {
         try {
            interval = TimeSpan.ParseExact(input, formats, culture);
            Console.WriteLine("{0} --> {1:c}", input, interval);
         }
         catch (FormatException) {
            Console.WriteLine("{0} --> Bad Format", input);
         }      
         catch (OverflowException) {
            Console.WriteLine("{0} --> Overflow", input);   
         }            
      }
   }
}
// The example displays the following output:
//       3 --> 03:00:00
//       16:42 --> 16:42:00
//       1:6:52:35.0625 --> Bad Format
//       1:6:52:35,0625 --> 1.06:52:35.0625000
open System
open System.Globalization

let inputs = [| "3"; "16:42"; "1:6:52:35.0625"; "1:6:52:35,0625" |] 
let formats = [| "g"; "G"; "%h" |]
let culture = CultureInfo "fr-FR"

// Parse each string in inputs using formats and the fr-FR culture.
for input in inputs do
    try
        let interval = TimeSpan.ParseExact(input, formats, culture)
        printfn $"{input} --> {interval:c}"
    with
    | :? FormatException ->
        printfn $"{input} --> Bad Format"
    | :? OverflowException ->
        printfn $"{input} --> Overflow"
// The example displays the following output:
//       3 --> 03:00:00
//       16:42 --> 16:42:00
//       1:6:52:35.0625 --> Bad Format
//       1:6:52:35,0625 --> 1.06:52:35.0625000
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim inputs() As String = { "3", "16:42", "1:6:52:35.0625", 
                                 "1:6:52:35,0625" } 
      Dim formats() As String = { "%h", "g", "G" }
      Dim interval As TimeSpan
      Dim culture As New CultureInfo("fr-FR")
      
      ' Parse each string in inputs using formats and the fr-FR culture.
      For Each input As String In inputs
         Try
            interval = TimeSpan.ParseExact(input, formats, culture)
            Console.WriteLine("{0} --> {1:c}", input, interval)   
         Catch e As FormatException
            Console.WriteLine("{0} --> Bad Format", input)   
         Catch e As OverflowException
            Console.WriteLine("{0} --> Overflow", input)   
         End Try            
      Next
   End Sub
End Module
' The example displays the following output:
'       3 --> 3.00:00:00
'       16:42 --> 16:42:00
'       1:6:52:35.0625 --> Bad Format
'       1:6:52:35,0625 --> 1.06:52:35.0625000

Comentarios

El ParseExact(String, String, IFormatProvider) método analiza la representación de cadena de un intervalo de tiempo, que debe estar en uno de los formatos definidos por el formats parámetro, excepto que se omiten los caracteres de espacio en blanco iniciales y finales. Dado que input debe cumplir exactamente uno de los formatos especificados en formats, siempre debe usar el control de excepciones al convertir una entrada de cadena por parte del usuario en un intervalo de tiempo. Si prefiere no usar el control de excepciones, puede llamar al TryParseExact(String, String[], IFormatProvider, TimeSpan) método en su lugar.

El formats parámetro es una matriz de cadenas cuyos elementos constan de un único especificador de formato estándar, o uno o varios especificadores de formato personalizado que definen el formato necesario de input. Para obtener más información sobre las cadenas de formato válidas, vea Cadenas de formato TimeSpan estándar y Cadenas de formato TimeSpan personalizados. input debe corresponder exactamente a un miembro de formats para que la operación de análisis se realice correctamente. La operación de análisis intenta coincidir input con cada elemento a formats partir del primer elemento de la matriz.

Importante

El ParseExact método usa las convenciones de la referencia cultural especificada por el formatProvider parámetro solo si la cadena de formato utilizada para analizar input es una cadena de formato estándar TimeSpan cuyo valor es "g" o "G". Las cadenas de formato estándar "c", "t" y "T" usan las convenciones de formato de la referencia cultural invariable. Las cadenas de formato personalizado definen el formato preciso de la cadena de entrada y usan caracteres literales para separar los componentes de un intervalo de tiempo.

El formatProvider parámetro es una IFormatProvider implementación que proporciona información específica de la referencia cultural sobre el formato de la cadena devuelta si la cadena de formato utilizada para analizar input es una cadena de formato estándar. El formatProvider parámetro puede ser cualquiera de los siguientes:

Si formatProvider es null, se usa el DateTimeFormatInfo objeto asociado a la referencia cultural actual.

Consulte también

Se aplica a

ParseExact(String, String, IFormatProvider)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de cadena de un intervalo de tiempo en su equivalente de TimeSpan, usando el formato especificado, así como la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

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

Parámetros

input
String

Cadena que especifica el intervalo de tiempo que se va a convertir.

format
String

Cadena de formato estándar o personalizado que define el formato requerido de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

Intervalo de tiempo que corresponde a input de acuerdo con lo especificado por format y formatProvider.

Excepciones

input es null.

input tiene un formato no válido.

input representa un número menor que TimeSpan.MinValue o mayor que TimeSpan.MaxValue.

o bien

Al menos uno de los componentes de días, horas, minutos o segundos de input está fuera del intervalo válido.

Ejemplos

En el ejemplo siguiente se usa el ParseExact(String, String, IFormatProvider) método para analizar varias representaciones de cadena de intervalos de tiempo mediante varias cadenas de formato y referencias culturales.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string intervalString, format;
      TimeSpan interval;
      CultureInfo culture;
      
      // Parse hour:minute value with "g" specifier current culture.
      intervalString = "17:14";
      format = "g";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", 
                           intervalString, format);
      }                     
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      }      
      
      // Parse hour:minute:second value with "G" specifier.
      intervalString = "17:14:48";
      format = "G";
      culture = CultureInfo.InvariantCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse hours:minute.second value with "G" specifier 
      // and current (en-US) culture.     
      intervalString = "17:14:48.153";
      format = "G";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 

      // Parse days:hours:minute.second value with "G" specifier 
      // and current (en-US) culture.     
      intervalString = "3:17:14:48.153";
      format = "G";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }   
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
            
      // Parse days:hours:minute.second value with "G" specifier 
      // and fr-FR culture.     
      intervalString = "3:17:14:48.153";
      format = "G";
      culture = new CultureInfo("fr-FR");
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse days:hours:minute.second value with "G" specifier 
      // and fr-FR culture.     
      intervalString = "3:17:14:48,153";
      format = "G";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }   
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 

      // Parse a single number using the "c" standard format string. 
      intervalString = "12";
      format = "c";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, null);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse a single number using the "%h" custom format string. 
      format = "%h";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, null);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      } 
      
      // Parse a single number using the "%s" custom format string. 
      format = "%s";
      try {
         interval = TimeSpan.ParseExact(intervalString, format, null);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      }
   }
}
// The example displays the following output:
//       '17:14' --> 17:14:00
//       '17:14:48': Bad Format for 'G'
//       '17:14:48.153': Bad Format for 'G'
//       '3:17:14:48.153' --> 3.17:14:48.1530000
//       '3:17:14:48.153': Bad Format for 'G'
//       '3:17:14:48,153' --> 3.17:14:48.1530000
//       '12' --> 12.00:00:00
//       '12' --> 12:00:00
//       '12' --> 00:00:12
open System
open System.Globalization

do
    // Parse hour:minute value with "g" specifier current culture.
    let intervalString = "17:14"
    let format = "g"
    let culture = CultureInfo.CurrentCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse hour:minute:second value with "G" specifier.
    let intervalString = "17:14:48"
    let format = "G"
    let culture = CultureInfo.InvariantCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse hours:minute.second value with "G" specifier 
    // and current (en-US) culture.     
    let intervalString = "17:14:48.153"
    let format = "G"
    let culture = CultureInfo.CurrentCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"

    // Parse days:hours:minute.second value with "G" specifier 
    // and current (en-US) culture.     
    let intervalString = "3:17:14:48.153"
    let format = "G"
    let culture = CultureInfo.CurrentCulture
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
        
    // Parse days:hours:minute.second value with "G" specifier 
    // and fr-FR culture.     
    let intervalString = "3:17:14:48.153"
    let format = "G"
    let culture = CultureInfo "fr-FR"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse days:hours:minute.second value with "G" specifier 
    // and fr-FR culture.     
    let intervalString = "3:17:14:48,153"
    let format = "G"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, culture)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"

    // Parse a single number using the "c" standard format string. 
    let intervalString = "12"
    let format = "c"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null)
        printfn $"'{intervalString}' --> {interval}"
    with
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse a single number using the "%h" custom format string. 
    let format = "%h"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
    
    // Parse a single number using the "%s" custom format string. 
    let format = "%s"
    try
        let interval = TimeSpan.ParseExact(intervalString, format, null)
        printfn $"'{intervalString}' --> {interval}"
    with 
    | :? FormatException ->
        printfn $"'{intervalString}': Bad Format for '{format}'"
    | :? OverflowException ->
        printfn $"'{intervalString}': Overflow"
// The example displays the following output:
//       '17:14' --> 17:14:00
//       '17:14:48': Bad Format for 'G'
//       '17:14:48.153': Bad Format for 'G'
//       '3:17:14:48.153' --> 3.17:14:48.1530000
//       '3:17:14:48.153': Bad Format for 'G'
//       '3:17:14:48,153' --> 3.17:14:48.1530000
//       '12' --> 12.00:00:00
//       '12' --> 12:00:00
//       '12' --> 00:00:12
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim intervalString, format As String
      Dim interval As TimeSpan
      Dim culture As CultureInfo
      
      ' Parse hour:minute value with "g" specifier current culture.
      intervalString = "17:14"
      format = "g"
      culture = CultureInfo.CurrentCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try      
      
      ' Parse hour:minute:second value with "G" specifier.
      intervalString = "17:14:48"
      format = "G"
      culture = CultureInfo.InvariantCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse hours:minute.second value with "G" specifier 
      ' and current (en-US) culture.     
      intervalString = "17:14:48.153"
      format = "G"
      culture = CultureInfo.CurrentCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 

      ' Parse days:hours:minute.second value with "G" specifier 
      ' and current (en-US) culture.     
      intervalString = "3:17:14:48.153"
      format = "G"
      culture = CultureInfo.CurrentCulture
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
            
      ' Parse days:hours:minute.second value with "G" specifier 
      ' and fr-FR culture.     
      intervalString = "3:17:14:48.153"
      format = "G"
      culture = New CultureInfo("fr-FR")
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse days:hours:minute.second value with "G" specifier 
      ' and fr-FR culture.     
      intervalString = "3:17:14:48,153"
      format = "G"
      culture = New CultureInfo("fr-FR")
      Try
         interval = TimeSpan.ParseExact(intervalString, format, culture)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 

      ' Parse a single number using the "c" standard format string. 
      intervalString = "12"
      format = "c"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, Nothing)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse a single number using the "%h" custom format string. 
      format = "%h"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, Nothing)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
      
      ' Parse a single number using the "%s" custom format string. 
      format = "%s"
      Try
         interval = TimeSpan.ParseExact(intervalString, format, Nothing)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Catch e As FormatException
         Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format)
      Catch e As OverflowException
         Console.WriteLine("'{0}': Overflow", intervalString)
      End Try 
   End Sub
End Module
' The example displays the following output:
'       '17:14' --> 17:14:00
'       '17:14:48': Bad Format for 'G'
'       '17:14:48.153': Bad Format for 'G'
'       '3:17:14:48.153' --> 3.17:14:48.1530000
'       '3:17:14:48.153': Bad Format for 'G'
'       '3:17:14:48,153' --> 3.17:14:48.1530000
'       '12' --> 12.00:00:00
'       '12' --> 12:00:00
'       '12' --> 00:00:12

Comentarios

El ParseExact(String, String, IFormatProvider) método analiza la representación de cadena de un intervalo de tiempo, que debe estar en el formato definido por el format parámetro, excepto que se omiten los caracteres de espacio en blanco iniciales y finales. Dado que input debe cumplir exactamente el formato de , siempre debe usar el control de excepciones al convertir una entrada de cadena por parte del usuario en un intervalo de format tiempo. Si prefiere no usar el control de excepciones, puede llamar al TryParseExact(String, String, IFormatProvider, TimeSpan) método en su lugar.

El format parámetro es una cadena que contiene un único especificador de formato estándar o uno o varios especificadores de formato personalizado que definen el formato necesario de input. Para obtener más información sobre las cadenas de formato válidas, vea Cadenas de formato TimeSpan estándar y Cadenas de formato TimeSpan personalizados.

Importante

El ParseExact método usa las convenciones de la referencia cultural especificada por el formatProvider parámetro solo si format es una cadena de formato estándar TimeSpan cuyo valor es "g" o "G". Las cadenas de formato estándar "c", "t" y "T" usan las convenciones de formato de la referencia cultural invariable. Las cadenas de formato personalizado definen el formato preciso de la cadena de entrada y usan caracteres literales para separar los componentes de un intervalo de tiempo.

El formatProvider parámetro es una IFormatProvider implementación que proporciona información específica de la referencia cultural sobre el formato de la cadena devuelta si format es una cadena de formato estándar. El formatProvider parámetro puede ser cualquiera de los siguientes:

Si formatProvider es null, se usa el DateTimeFormatInfo objeto asociado a la referencia cultural actual.

Consulte también

Se aplica a

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Convierte la representación de carácter de un intervalo de tiempo en su valor TimeSpan equivalente, mediante el formato especificado y la información de formato específica de la referencia cultural. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.

public static TimeSpan ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None);
public static TimeSpan ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None);
static member ParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.TimeSpanStyles -> TimeSpan
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, Optional styles As TimeSpanStyles = System.Globalization.TimeSpanStyles.None) As TimeSpan

Parámetros

input
ReadOnlySpan<Char>

Un intervalo que especifica el intervalo de tiempo que se va a convertir.

format
ReadOnlySpan<Char>

Cadena de formato estándar o personalizado que define el formato requerido de input.

formatProvider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

styles
TimeSpanStyles

Combinación bit a bit de valores de enumeración que define los elementos de estilo que pueden estar presentes en input.

Devoluciones

Intervalo de tiempo que corresponde a input de acuerdo con lo especificado por format y formatProvider.

Se aplica a