TimeSpan.ParseExact Méthode

Définition

Convertit la représentation sous forme de chaîne d'un intervalle de temps en TimeSpan équivalent. Le format de la représentation sous forme de chaîne doit correspondre exactement à un format spécifié.

Surcharges

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des styles et des informations de format spécifiques à la culture spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des formats, des informations de format spécifiques à la culture et des styles spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des formats, des informations de format spécifiques à la culture et des styles spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

ParseExact(String, String[], IFormatProvider)

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide du tableau de chaînes de format et des informations de format spécifiques à la culture spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

ParseExact(String, String, IFormatProvider)

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des informations de format spécifiques à la culture spécifiées. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

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

Convertit l’étendue de caractères d'un intervalle de temps dans son équivalent TimeSpan à l'aide des informations de format spécifiques à la culture spécifiées. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des styles et des informations de format spécifiques à la culture spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

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

Paramètres

input
String

Chaîne qui spécifie l'intervalle de temps à convertir.

format
String

Chaîne de format standard ou personnalisée qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

styles
TimeSpanStyles

Combinaison de bits de valeurs d'énumération qui définit les éléments de style pouvant être présents dans input.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par format, formatProvider et styles.

Exceptions

styles est une valeur TimeSpanStyles non valide.

input a la valeur null.

input a un format non valide.

input représente un nombre inférieur à TimeSpan.MinValue ou supérieur à TimeSpan.MaxValue.

- ou -

Au moins un des composants des jours, heures, minutes ou secondes dans input est en dehors de sa plage valide.

Exemples

L’exemple suivant utilise la ParseExact(String, String, IFormatProvider) méthode pour analyser plusieurs représentations de chaîne d’intervalles de temps à l’aide de différentes chaînes et cultures de format. Il utilise également la TimeSpanStyles.AssumeNegative valeur pour interpréter chaque chaîne comme un intervalle de temps négatif. La sortie de l’exemple montre que le style affecte la TimeSpanStyles.AssumeNegative valeur de retour uniquement lorsqu’il est utilisé avec des chaînes de format personnalisées.

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

Remarques

La ParseExact méthode analyse la représentation sous forme de chaîne d’un intervalle de temps, qui doit être au format défini par le format paramètre, sauf que les espaces blancs de début et de fin sont ignorés. Étant donné que input doit être conforme au format de format exactement, vous devez toujours utiliser la gestion des exceptions lors de la conversion d’une entrée de chaîne par l’utilisateur en intervalle de temps. Si vous préférez ne pas utiliser la gestion des exceptions, vous pouvez appeler la méthode à la TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) place.

Le format paramètre est une chaîne qui contient un spécificateur de format standard unique ou un ou plusieurs spécificateurs de format personnalisés qui définissent le format requis de input. Pour plus d’informations sur les chaînes de format valides, consultez Chaînes de format TimeSpan standard et Chaînes de format TimeSpan personnalisées.

Important

La ParseExact méthode utilise les conventions de la culture spécifiée par le formatProvider paramètre uniquement si format est une chaîne de format standard TimeSpan dont la valeur est « g » ou « G ». Les chaînes de format standard « c », « t » et « T » utilisent les conventions de mise en forme de la culture invariante. Les chaînes de format personnalisées définissent le format précis de la chaîne d’entrée et utilisent des caractères littéraux pour séparer les composants d’un intervalle de temps.

Le formatProvider paramètre est une IFormatProvider implémentation qui fournit des informations spécifiques à la culture sur le format de la chaîne retournée si format est une chaîne de format standard. Le formatProvider paramètre peut être l’un des éléments suivants :

Si formatProvider est null, l’objet DateTimeFormatInfo associé à la culture actuelle est utilisé.

Le styles paramètre affecte l’interprétation des chaînes analysées à l’aide de chaînes de format personnalisées. Il détermine si input est interprété comme un intervalle de temps négatif uniquement si un signe négatif est présent (TimeSpanStyles.None), ou s’il est toujours interprété comme un intervalle de temps négatif (TimeSpanStyles.AssumeNegative). Si TimeSpanStyles.AssumeNegative n’est pas utilisé, format doit inclure un symbole de signe négatif littéral (tel que « \- ») pour analyser correctement un intervalle de temps négatif.

Voir aussi

S’applique à

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

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des formats, des informations de format spécifiques à la culture et des styles spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

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

Paramètres

input
ReadOnlySpan<Char>

Étendue qui spécifie l'intervalle de temps à convertir.

formats
String[]

Tableau de chaînes de format standard ou personnalisé qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

styles
TimeSpanStyles

Combinaison de bits de valeurs d'énumération qui définit les éléments de style pouvant être présents dans l'entrée.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par formats, formatProvider et styles.

S’applique à

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

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des formats, des informations de format spécifiques à la culture et des styles spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

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

Paramètres

input
String

Chaîne qui spécifie l'intervalle de temps à convertir.

formats
String[]

Tableau de chaînes de format standard ou personnalisé qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

styles
TimeSpanStyles

Combinaison de bits de valeurs d'énumération qui définit les éléments de style pouvant être présents dans l'entrée.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par formats, formatProvider et styles.

Exceptions

styles est une valeur TimeSpanStyles non valide.

input a la valeur null.

input a un format non valide.

input représente un nombre inférieur à TimeSpan.MinValue ou supérieur à TimeSpan.MaxValue.

- ou -

Au moins un des composants des jours, heures, minutes ou secondes dans input est en dehors de sa plage valide.

Exemples

L’exemple suivant appelle la ParseExact(String, String[], IFormatProvider, TimeSpanStyles) méthode pour convertir chaque élément d’un tableau de chaînes en valeur TimeSpan . Les chaînes peuvent représenter un intervalle de temps au format court général ou au format long général.

En outre, l’exemple modifie la façon dont les méthodes d’analyse de l’intervalle de temps interprètent un chiffre unique. En règle générale, un chiffre unique est interprété comme le nombre de jours dans un intervalle de temps. Au lieu de cela, la %h chaîne de format personnalisée est utilisée pour interpréter un chiffre unique comme le nombre d’heures. Pour que cette modification soit effective, notez que la %h chaîne de format personnalisée doit précéder les autres chaînes de format dans le formats tableau. Notez également dans la sortie que l’indicateur TimeSpanStyles.AssumeNegative spécifié dans l’appel de méthode est utilisé uniquement lors de l’analyse d’une chaîne avec ce spécificateur de format.

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

Remarques

La ParseExact(String, String[], IFormatProvider, TimeSpanStyles) méthode analyse la représentation sous forme de chaîne d’un intervalle de temps, qui doit être dans l’un des formats définis par le formats paramètre, sauf que les espaces blancs de début et de fin sont ignorés. Étant donné que input doit se conformer exactement à l’un des formats spécifiés dans formats, vous devez toujours utiliser la gestion des exceptions lors de la conversion d’une entrée de chaîne par l’utilisateur en intervalle de temps. Si vous préférez ne pas utiliser la gestion des exceptions, vous pouvez appeler la méthode à la TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) place.

Le formats paramètre est un tableau de chaînes dont les éléments se composent d’un spécificateur de format standard unique ou d’un ou plusieurs spécificateurs de format personnalisés qui définissent le format requis de input. Pour plus d’informations sur les chaînes de format valides, consultez Chaînes de format TimeSpan standard et Chaînes de format TimeSpan personnalisées. input doit correspondre exactement à un membre de formats pour que l’opération d’analyse réussisse. L’opération d’analyse tente de correspondre à input chaque élément en formats commençant par le premier élément du tableau.

Important

La ParseExact méthode utilise les conventions de la culture spécifiée par le paramètre uniquement si la formatProvider chaîne de format utilisée pour analyser input est une chaîne de format standard TimeSpan dont la valeur est « g » ou « G ». Les chaînes de format standard « c », « t » et « T » utilisent les conventions de mise en forme de la culture invariante. Les chaînes de format personnalisées définissent le format précis de la chaîne d’entrée et utilisent des caractères littéraux pour séparer les composants d’un intervalle de temps.

Le formatProvider paramètre est une IFormatProvider implémentation qui fournit des informations spécifiques à la culture sur le format de la chaîne retournée si la chaîne de format utilisée pour l’analyse input est une chaîne de format standard. Le formatProvider paramètre peut être l’un des éléments suivants :

Si formatProvider est null, l’objet DateTimeFormatInfo associé à la culture actuelle est utilisé.

Le styles paramètre affecte l’interprétation des chaînes analysées à l’aide de chaînes de format personnalisées. Il détermine si input est interprété comme un intervalle de temps négatif uniquement si un signe négatif est présent (TimeSpanStyles.None), ou s’il est toujours interprété comme un intervalle de temps négatif (TimeSpanStyles.AssumeNegative). Si TimeSpanStyles.AssumeNegative n’est pas utilisé, format doit inclure un symbole de signe négatif littéral (tel que « \- ») pour analyser correctement un intervalle de temps négatif.

Voir aussi

S’applique à

ParseExact(String, String[], IFormatProvider)

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide du tableau de chaînes de format et des informations de format spécifiques à la culture spécifiés. Le format de la représentation sous forme de chaîne doit correspondre exactement à l'un des formats spécifiés.

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

Paramètres

input
String

Chaîne qui spécifie l'intervalle de temps à convertir.

formats
String[]

Tableau de chaînes de format standard ou personnalisé qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par formats et formatProvider.

Exceptions

input a la valeur null.

input a un format non valide.

input représente un nombre inférieur à TimeSpan.MinValue ou supérieur à TimeSpan.MaxValue.

- ou -

Au moins un des composants des jours, heures, minutes ou secondes dans input est en dehors de sa plage valide.

Exemples

L’exemple suivant appelle la ParseExact(String, String[], IFormatProvider) méthode pour convertir chaque élément d’un tableau de chaînes en valeur TimeSpan . L’exemple interprète les chaînes à l’aide des conventions de mise en forme de la culture Français - France (« fr-FR »). Les chaînes peuvent représenter un intervalle de temps au format court général ou au format long général.

En outre, l’exemple modifie la façon dont les méthodes d’analyse de l’intervalle de temps interprètent un chiffre unique. En règle générale, un chiffre unique est interprété comme le nombre de jours dans un intervalle de temps. Au lieu de cela, la %h chaîne de format personnalisée est utilisée pour interpréter un chiffre unique comme le nombre d’heures. Pour que cette modification soit effective, notez que la %h chaîne de format personnalisée doit précéder les autres chaînes de format dans le formats tableau.

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

Remarques

La ParseExact(String, String, IFormatProvider) méthode analyse la représentation sous forme de chaîne d’un intervalle de temps, qui doit être dans l’un des formats définis par le formats paramètre, sauf que les espaces blancs de début et de fin sont ignorés. Étant donné que input doit se conformer exactement à l’un des formats spécifiés dans formats, vous devez toujours utiliser la gestion des exceptions lors de la conversion d’une entrée de chaîne par l’utilisateur en intervalle de temps. Si vous préférez ne pas utiliser la gestion des exceptions, vous pouvez appeler la méthode à la TryParseExact(String, String[], IFormatProvider, TimeSpan) place.

Le formats paramètre est un tableau de chaînes dont les éléments se composent d’un spécificateur de format standard unique ou d’un ou plusieurs spécificateurs de format personnalisés qui définissent le format requis de input. Pour plus d’informations sur les chaînes de format valides, consultez Chaînes de format TimeSpan standard et Chaînes de format TimeSpan personnalisées. input doit correspondre exactement à un membre de formats pour que l’opération d’analyse réussisse. L’opération d’analyse tente de correspondre à input chaque élément en formats commençant par le premier élément du tableau.

Important

La ParseExact méthode utilise les conventions de la culture spécifiée par le paramètre uniquement si la formatProvider chaîne de format utilisée pour analyser input est une chaîne de format standard TimeSpan dont la valeur est « g » ou « G ». Les chaînes de format standard « c », « t » et « T » utilisent les conventions de mise en forme de la culture invariante. Les chaînes de format personnalisées définissent le format précis de la chaîne d’entrée et utilisent des caractères littéraux pour séparer les composants d’un intervalle de temps.

Le formatProvider paramètre est une IFormatProvider implémentation qui fournit des informations spécifiques à la culture sur le format de la chaîne retournée si la chaîne de format utilisée pour l’analyse input est une chaîne de format standard. Le formatProvider paramètre peut être l’un des éléments suivants :

Si formatProvider est null, l’objet DateTimeFormatInfo associé à la culture actuelle est utilisé.

Voir aussi

S’applique à

ParseExact(String, String, IFormatProvider)

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

Convertit la représentation sous forme de chaîne d'un intervalle de temps dans son équivalent TimeSpan à l'aide des informations de format spécifiques à la culture spécifiées. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

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

Paramètres

input
String

Chaîne qui spécifie l'intervalle de temps à convertir.

format
String

Chaîne de format standard ou personnalisée qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par format et formatProvider.

Exceptions

input a la valeur null.

input a un format non valide.

input représente un nombre inférieur à TimeSpan.MinValue ou supérieur à TimeSpan.MaxValue.

- ou -

Au moins un des composants des jours, heures, minutes ou secondes dans input est en dehors de sa plage valide.

Exemples

L’exemple suivant utilise la ParseExact(String, String, IFormatProvider) méthode pour analyser plusieurs représentations de chaîne d’intervalles de temps à l’aide de différentes chaînes et cultures de format.

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

Remarques

La ParseExact(String, String, IFormatProvider) méthode analyse la représentation sous forme de chaîne d’un intervalle de temps, qui doit être au format défini par le format paramètre, sauf que les espaces blancs de début et de fin sont ignorés. Étant donné que input doit être conforme au format de format exactement, vous devez toujours utiliser la gestion des exceptions lors de la conversion d’une entrée de chaîne par l’utilisateur en intervalle de temps. Si vous préférez ne pas utiliser la gestion des exceptions, vous pouvez appeler la méthode à la TryParseExact(String, String, IFormatProvider, TimeSpan) place.

Le format paramètre est une chaîne qui contient un spécificateur de format standard unique ou un ou plusieurs spécificateurs de format personnalisés qui définissent le format requis de input. Pour plus d’informations sur les chaînes de format valides, consultez Chaînes de format TimeSpan standard et Chaînes de format TimeSpan personnalisées.

Important

La ParseExact méthode utilise les conventions de la culture spécifiée par le formatProvider paramètre uniquement si format est une chaîne de format standard TimeSpan dont la valeur est « g » ou « G ». Les chaînes de format standard « c », « t » et « T » utilisent les conventions de mise en forme de la culture invariante. Les chaînes de format personnalisées définissent le format précis de la chaîne d’entrée et utilisent des caractères littéraux pour séparer les composants d’un intervalle de temps.

Le formatProvider paramètre est une IFormatProvider implémentation qui fournit des informations spécifiques à la culture sur le format de la chaîne retournée si format est une chaîne de format standard. Le formatProvider paramètre peut être l’un des éléments suivants :

Si formatProvider est null, l’objet DateTimeFormatInfo associé à la culture actuelle est utilisé.

Voir aussi

S’applique à

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

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

Convertit l’étendue de caractères d'un intervalle de temps dans son équivalent TimeSpan à l'aide des informations de format spécifiques à la culture spécifiées. Le format de la représentation sous forme de chaîne doit correspondre exactement au format spécifié.

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

Paramètres

input
ReadOnlySpan<Char>

Étendue qui spécifie l'intervalle de temps à convertir.

format
ReadOnlySpan<Char>

Chaîne de format standard ou personnalisée qui définit le format requis pour input.

formatProvider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture.

styles
TimeSpanStyles

Combinaison de bits de valeurs d'énumération qui définit les éléments de style pouvant être présents dans input.

Retours

Intervalle de temps qui correspond à input, tel que spécifié par format et formatProvider.

S’applique à