Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

TimeSpan.ParseExact (Método) (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.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

public static TimeSpan ParseExact(
	string input,
	string format,
	IFormatProvider formatProvider
)

Parámetros

input
Type: System.String

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

format
Type: System.String

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

formatProvider
Type: System.IFormatProvider

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

Valor devuelto

Type: System.TimeSpan

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

Exception Condition
ArgumentNullException

El valor de input es null.

FormatException

input tiene un formato no válido.

OverflowException

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.

The M:System.TimeSpan.ParseExact(System.String,System.String,System.IFormatProvider) method parses the string representation of a time interval, which must be in the format defined by the format parameter, except that leading and trailing white-space characters are ignored. Because input must conform to the format of format exactly, you should always use exception handling when converting a string input by the user to a time interval. If you prefer not to use exception handling, you can call the M:System.TimeSpan.TryParseExact(System.String,System.String,System.IFormatProvider,System.TimeSpan@) method instead.

The format parameter is a string that contains either a single standard format specifier, or one or more custom format specifiers that define the required format of input. For more information about valid format strings, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.

System_CAPS_importantImportante

The M:System.TimeSpan.ParseExact(System.String,System.String,System.IFormatProvider) method uses the conventions of the culture specified by the formatProvider parameter only if format is a standard T:System.TimeSpan format string whose value is either "g" or "G". The "c", "t", and "T" standard format strings use the formatting conventions of the invariant culture. Custom format strings define the precise format of the input string and use literal characters to separate the components of a time interval.

The formatProvider parameter is an T:System.IFormatProvider implementation that provides culture-specific information about the format of the returned string if format is a standard format string. The formatProvider parameter can be any of the following:

  • A T:System.Globalization.CultureInfo object that represents the culture whose formatting conventions are to be reflected in the returned string. The T:System.Globalization.DateTimeFormatInfo object returned by the P:System.Globalization.CultureInfo.DateTimeFormat property defines the formatting of the returned string.

  • A T:System.Globalization.DateTimeFormatInfo object that defines the formatting of the returned string.

  • A custom object that implements the T:System.IFormatProvider interface. Its M:System.IFormatProvider.GetFormat(System.Type) method returns a T:System.Globalization.DateTimeFormatInfo object that provides formatting information.

If formatProvider is null, the T:System.Globalization.DateTimeFormatInfo object that is associated with the current culture is used.

The following example uses the M:System.TimeSpan.ParseExact(System.String,System.String,System.IFormatProvider) method to parse several string representations of time intervals using various format strings and cultures.

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

Universal Windows Platform
Disponible desde 4.5
.NET Framework
Disponible desde 4.0
Portable Class Library
Compatible con: portable .NET platforms
Silverlight
Disponible desde 4.0
Windows Phone Silverlight
Disponible desde 7.1
Windows Phone
Disponible desde 8.1
Volver al principio
Mostrar: