TimeSpan.ParseExact Metodo

Definizione

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan. Il formato della rappresentazione di stringa deve corrispondere esattamente a un formato specificato.

Overload

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando i formati, gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando i formati, gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

ParseExact(String, String[], IFormatProvider)

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando la matrice di stringhe di formato e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

ParseExact(String, String, IFormatProvider)

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

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

Converte l'intervallo di caratteri di un intervallo di tempo nell'equivalente TimeSpan usando le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

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

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

format
String

Stringa di formato standard o personalizzato che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Combinazione bit per bit di valori di enumerazione che definisce gli elementi di stile che possono essere presenti in input.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da format, formatProvider e styles.

Eccezioni

styles è un valore TimeSpanStyles non valido.

input è null.

Il formato di input non è valido.

input rappresenta un numero minore di TimeSpan.MinValue o maggiore di TimeSpan.MaxValue.

-oppure-

Almeno uno dei componenti giorni, ore, minuti o secondi in input non rientra nell'intervallo valido.

Esempio

Nell'esempio seguente viene usato il ParseExact(String, String, IFormatProvider) metodo per analizzare diverse rappresentazioni di stringhe di intervalli di tempo usando varie stringhe di formato e impostazioni cultura. Usa anche il TimeSpanStyles.AssumeNegative valore per interpretare ogni stringa come intervallo di tempo negativo. L'output dell'esempio illustra che lo TimeSpanStyles.AssumeNegative stile influisce sul valore restituito solo quando viene usato con stringhe di formato personalizzate.

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

Commenti

Il ParseExact metodo analizza la rappresentazione stringa di un intervallo di tempo, che deve essere nel formato definito dal format parametro, ad eccezione del fatto che i caratteri di spazi vuoti iniziali e finali vengono ignorati. Poiché input deve essere conforme al formato esatto, è consigliabile usare sempre la gestione delle eccezioni durante la conversione di format un input stringa dall'utente in un intervallo di tempo. Se si preferisce non usare la gestione delle eccezioni, è possibile chiamare invece il TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) metodo.

Il format parametro è una stringa contenente un singolo identificatore di formato standard o uno o più identificatori di formato personalizzati che definiscono il formato richiesto di input. Per altre informazioni sulle stringhe di formato valide, vedere Stringhe di formato TimeSpan standard e Stringhe di formato TimeSpan personalizzato.

Importante

Il ParseExact metodo usa le convenzioni delle impostazioni cultura specificate dal formatProvider parametro solo se format è una stringa di formato standard TimeSpan il cui valore è "g" o "G". Le stringhe di formato standard "c", "t" e "T" usano le convenzioni di formattazione delle impostazioni cultura invarianti. Le stringhe di formato personalizzato definiscono il formato preciso della stringa di input e usano caratteri letterali per separare i componenti di un intervallo di tempo.

Il formatProvider parametro è un'implementazione IFormatProvider che fornisce informazioni specifiche delle impostazioni cultura sul formato della stringa restituita se format è una stringa di formato standard. Il formatProvider parametro può essere uno dei seguenti:

Se formatProvider è null, viene usato l'oggetto DateTimeFormatInfo associato alle impostazioni cultura correnti.

Il styles parametro influisce sull'interpretazione delle stringhe analizzate usando stringhe di formato personalizzate. Determina se input viene interpretato come intervallo di tempo negativo solo se è presente un segno negativo (TimeSpanStyles.None) o se viene sempre interpretato come intervallo di tempo negativo (TimeSpanStyles.AssumeNegative). Se TimeSpanStyles.AssumeNegative non viene usato, format deve includere un simbolo di segno negativo letterale (ad esempio "\-") per analizzare correttamente un intervallo di tempo negativo.

Vedi anche

Si applica a

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

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando i formati, gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

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

Parametri

input
ReadOnlySpan<Char>

Intervallo che specifica l'intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe in formato standard o personalizzato che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Combinazione bit per bit di valori di enumerazione che definisce gli elementi di stile che possono essere presenti in input.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da formats, formatProvider e styles.

Si applica a

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

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando i formati, gli stili e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

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

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe in formato standard o personalizzato che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Combinazione bit per bit di valori di enumerazione che definisce gli elementi di stile che possono essere presenti in input.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da formats, formatProvider e styles.

Eccezioni

styles è un valore TimeSpanStyles non valido.

input è null.

Il formato di input non è valido.

input rappresenta un numero minore di TimeSpan.MinValue o maggiore di TimeSpan.MaxValue.

-oppure-

Almeno uno dei componenti giorni, ore, minuti o secondi in input non rientra nell'intervallo valido.

Esempio

Nell'esempio seguente viene chiamato il ParseExact(String, String[], IFormatProvider, TimeSpanStyles) metodo per convertire ogni elemento di una matrice di stringhe in un TimeSpan valore. Le stringhe possono rappresentare un intervallo di tempo nel formato breve generale o nel formato lungo generale.

Inoltre, nell'esempio viene modificato il modo in cui i metodi di analisi dell'intervallo di tempo interpretano una singola cifra. In genere, una singola cifra viene interpretata come numero di giorni in un intervallo di tempo. La stringa di formato personalizzato viene invece %h usata per interpretare una singola cifra come numero di ore. Affinché questa modifica sia efficace, tenere presente che la %h stringa di formato personalizzata deve precedere le altre stringhe di formato nella formats matrice. Si noti anche dall'output che il flag specificato nella chiamata al metodo viene usato solo durante l'analisi TimeSpanStyles.AssumeNegative di una stringa con questo identificatore di 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

Commenti

Il ParseExact(String, String[], IFormatProvider, TimeSpanStyles) metodo analizza la rappresentazione stringa di un intervallo di tempo, che deve trovarsi in uno dei formati definiti dal formats parametro, ad eccezione del fatto che i caratteri di spazi vuoti iniziali e finali vengono ignorati. Poiché input deve essere esattamente conforme a uno dei formati specificati in formats, è consigliabile usare sempre la gestione delle eccezioni durante la conversione di un input stringa da parte dell'utente in un intervallo di tempo. Se si preferisce non usare la gestione delle eccezioni, è possibile chiamare invece il TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) metodo.

Il formats parametro è una matrice di stringhe i cui elementi sono costituiti da un singolo identificatore di formato standard o uno o più identificatori di formato personalizzati che definiscono il formato richiesto di input. Per altre informazioni sulle stringhe di formato valide, vedere Stringhe di formato TimeSpan standard e Stringhe di formato TimeSpan personalizzato. input deve corrispondere esattamente a un membro dell'operazione di formats analisi per l'esito positivo dell'operazione di analisi. L'operazione di analisi tenta di corrispondere input a ogni elemento a formats partire dal primo elemento della matrice.

Importante

Il ParseExact metodo usa le convenzioni delle impostazioni cultura specificate dal formatProvider parametro solo se la stringa di formato usata per l'analisi input è una stringa di formato standard TimeSpan il cui valore è "g" o "G". Le stringhe di formato standard "c", "t" e "T" usano le convenzioni di formattazione delle impostazioni cultura invarianti. Le stringhe di formato personalizzato definiscono il formato preciso della stringa di input e usano caratteri letterali per separare i componenti di un intervallo di tempo.

Il formatProvider parametro è un'implementazione IFormatProviderinput che fornisce informazioni specifiche delle impostazioni cultura sul formato della stringa restituita se la stringa di formato utilizzata per l'analisi è una stringa di formato standard. Il formatProvider parametro può essere uno dei seguenti:

Se formatProvider è null, viene usato l'oggetto DateTimeFormatInfo associato alle impostazioni cultura correnti.

Il styles parametro influisce sull'interpretazione delle stringhe analizzate usando stringhe di formato personalizzate. Determina se input viene interpretato come intervallo di tempo negativo solo se è presente un segno negativo (TimeSpanStyles.None) o se viene sempre interpretato come intervallo di tempo negativo (TimeSpanStyles.AssumeNegative). Se TimeSpanStyles.AssumeNegative non viene usato, format deve includere un simbolo di segno negativo letterale (ad esempio "\-") per analizzare correttamente un intervallo di tempo negativo.

Vedi anche

Si applica a

ParseExact(String, String[], IFormatProvider)

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando la matrice di stringhe di formato e le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente a uno dei formati specificati.

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

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe di formato standard o personalizzate che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da formats e formatProvider.

Eccezioni

input è null.

Il formato di input non è valido.

input rappresenta un numero minore di TimeSpan.MinValue o maggiore di TimeSpan.MaxValue.

-oppure-

Almeno uno dei componenti giorni, ore, minuti o secondi in input non rientra nell'intervallo valido.

Esempio

Nell'esempio seguente viene chiamato il ParseExact(String, String[], IFormatProvider) metodo per convertire ogni elemento di una matrice di stringhe in un TimeSpan valore. L'esempio interpreta le stringhe usando le convenzioni di formattazione delle impostazioni cultura francese - Francia ("fr-FR"). Le stringhe possono rappresentare un intervallo di tempo nel formato breve generale o nel formato lungo generale.

Inoltre, nell'esempio viene modificato il modo in cui i metodi di analisi dell'intervallo di tempo interpretano una singola cifra. In genere, una singola cifra viene interpretata come numero di giorni in un intervallo di tempo. La stringa di formato personalizzato viene invece %h usata per interpretare una singola cifra come numero di ore. Affinché questa modifica sia efficace, tenere presente che la %h stringa di formato personalizzata deve precedere le altre stringhe di formato nella formats matrice.

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

Commenti

Il ParseExact(String, String, IFormatProvider) metodo analizza la rappresentazione stringa di un intervallo di tempo, che deve trovarsi in uno dei formati definiti dal formats parametro, ad eccezione del fatto che i caratteri di spazi vuoti iniziali e finali vengono ignorati. Poiché input deve essere esattamente conforme a uno dei formati specificati in formats, è consigliabile usare sempre la gestione delle eccezioni durante la conversione di un input stringa da parte dell'utente in un intervallo di tempo. Se si preferisce non usare la gestione delle eccezioni, è possibile chiamare invece il TryParseExact(String, String[], IFormatProvider, TimeSpan) metodo.

Il formats parametro è una matrice di stringhe i cui elementi sono costituiti da un singolo identificatore di formato standard o uno o più identificatori di formato personalizzati che definiscono il formato richiesto di input. Per altre informazioni sulle stringhe di formato valide, vedere Stringhe di formato TimeSpan standard e Stringhe di formato TimeSpan personalizzato. input deve corrispondere esattamente a un membro dell'operazione di formats analisi per l'esito positivo dell'operazione di analisi. L'operazione di analisi tenta di corrispondere input a ogni elemento a formats partire dal primo elemento della matrice.

Importante

Il ParseExact metodo usa le convenzioni delle impostazioni cultura specificate dal formatProvider parametro solo se la stringa di formato usata per l'analisi input è una stringa di formato standard TimeSpan il cui valore è "g" o "G". Le stringhe di formato standard "c", "t" e "T" usano le convenzioni di formattazione delle impostazioni cultura invarianti. Le stringhe di formato personalizzato definiscono il formato preciso della stringa di input e usano caratteri letterali per separare i componenti di un intervallo di tempo.

Il formatProvider parametro è un'implementazione IFormatProviderinput che fornisce informazioni specifiche delle impostazioni cultura sul formato della stringa restituita se la stringa di formato utilizzata per l'analisi è una stringa di formato standard. Il formatProvider parametro può essere uno dei seguenti:

Se formatProvider è null, viene usato l'oggetto DateTimeFormatInfo associato alle impostazioni cultura correnti.

Vedi anche

Si applica a

ParseExact(String, String, IFormatProvider)

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

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan usando le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

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

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

format
String

Stringa di formato standard o personalizzato che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da format e formatProvider.

Eccezioni

input è null.

Il formato di input non è valido.

input rappresenta un numero minore di TimeSpan.MinValue o maggiore di TimeSpan.MaxValue.

-oppure-

Almeno uno dei componenti giorni, ore, minuti o secondi in input non rientra nell'intervallo valido.

Esempio

Nell'esempio seguente viene usato il ParseExact(String, String, IFormatProvider) metodo per analizzare diverse rappresentazioni di stringhe di intervalli di tempo usando varie stringhe di formato e impostazioni cultura.

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

Commenti

Il ParseExact(String, String, IFormatProvider) metodo analizza la rappresentazione stringa di un intervallo di tempo, che deve essere nel formato definito dal format parametro, ad eccezione del fatto che i caratteri di spazi vuoti iniziali e finali vengono ignorati. Poiché input deve essere conforme al formato esatto, è consigliabile usare sempre la gestione delle eccezioni durante la conversione di format un input stringa dall'utente in un intervallo di tempo. Se si preferisce non usare la gestione delle eccezioni, è possibile chiamare invece il TryParseExact(String, String, IFormatProvider, TimeSpan) metodo.

Il format parametro è una stringa contenente un singolo identificatore di formato standard o uno o più identificatori di formato personalizzati che definiscono il formato richiesto di input. Per altre informazioni sulle stringhe di formato valide, vedere Stringhe di formato TimeSpan standard e Stringhe di formato TimeSpan personalizzato.

Importante

Il ParseExact metodo usa le convenzioni delle impostazioni cultura specificate dal formatProvider parametro solo se format è una stringa di formato standard TimeSpan il cui valore è "g" o "G". Le stringhe di formato standard "c", "t" e "T" usano le convenzioni di formattazione delle impostazioni cultura invarianti. Le stringhe di formato personalizzato definiscono il formato preciso della stringa di input e usano caratteri letterali per separare i componenti di un intervallo di tempo.

Il formatProvider parametro è un'implementazione IFormatProvider che fornisce informazioni specifiche delle impostazioni cultura sul formato della stringa restituita se format è una stringa di formato standard. Il formatProvider parametro può essere uno dei seguenti:

Se formatProvider è null, viene usato l'oggetto DateTimeFormatInfo associato alle impostazioni cultura correnti.

Vedi anche

Si applica a

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

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

Converte l'intervallo di caratteri di un intervallo di tempo nell'equivalente TimeSpan usando le informazioni sul formato specifiche delle impostazioni cultura indicate. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

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

Parametri

input
ReadOnlySpan<Char>

Intervallo che specifica l'intervallo di tempo da convertire.

format
ReadOnlySpan<Char>

Stringa di formato standard o personalizzato che definisce il formato richiesto di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Combinazione bit per bit di valori di enumerazione che definisce gli elementi di stile che possono essere presenti in input.

Restituisce

Intervallo di tempo che corrisponde a input, come specificato da format e formatProvider.

Si applica a