TimeSpan.TryParseExact Metodo

Definizione

Converte la rappresentazione di stringa di un intervallo di tempo nell'equivalente TimeSpan e restituisce un valore che indica se la conversione è stata eseguita correttamente. Il formato della rappresentazione di stringa deve corrispondere esattamente a un formato specificato.

Overload

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles, TimeSpan)

Converte la rappresentazione intervallo specificata di un intervallo di tempo nell'equivalente TimeSpan usando il formato, le informazioni sul formato specifiche delle impostazioni cultura e gli stili specificati e restituisce un valore che indica se la conversione è stata eseguita correttamente. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan)

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

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

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

TryParseExact(String, String[], IFormatProvider, TimeSpan)

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

TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan)

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

TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpan)

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

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

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

TryParseExact(String, String, IFormatProvider, TimeSpan)

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.

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles, TimeSpan)

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

Converte la rappresentazione intervallo specificata di un intervallo di tempo nell'equivalente TimeSpan usando il formato, le informazioni sul formato specifiche delle impostazioni cultura e gli stili specificati e restituisce un valore che indica se la conversione è stata eseguita correttamente. Il formato della rappresentazione di stringa deve corrispondere esattamente al formato specificato.

public:
 static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
static member TryParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.TimeSpanStyles * TimeSpan -> bool
Public Shared Function TryParseExact (input As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, styles As TimeSpanStyles, ByRef result As TimeSpan) As Boolean

Parametri

input
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano un intervallo di tempo da convertire.

format
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano una stringa di formato standard o personalizzato che definisce il formato accettabile di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Uno o più valori di enumerazione che indicano lo stile di input.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan)

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

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

public:
 static bool TryParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (string input, string format, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (string? input, string? format, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (string? input, string format, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
static member TryParseExact : string * string * IFormatProvider * System.Globalization.TimeSpanStyles * TimeSpan -> bool
Public Shared Function TryParseExact (input As String, format As String, formatProvider As IFormatProvider, styles As TimeSpanStyles, ByRef result As TimeSpan) As Boolean

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

Uno o più valori di enumerazione che indicano lo stile di input.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene usato il ParseExact(String, String, IFormatProvider) metodo per analizzare diverse rappresentazioni di stringa 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;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
      
      // Parse hour:minute:second value with "g" specifier.
      intervalString = "17:14:48";
      format = "g";
      culture = CultureInfo.InvariantCulture;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
      
      // Parse hours:minute.second value with custom format specifier.     
      intervalString = "17:14:48.153";
      format = @"h\:mm\:ss\.fff";
      culture = null;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);   

      // 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;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);   
            
      // 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;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
      
      // 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");
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);

      // Parse a single number using the "c" standard format string. 
      intervalString = "12";
      format = "c";
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 null, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
      
      // Parse a single number using the "%h" custom format string. 
      format = "%h";
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 null, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
      
      // Parse a single number using the "%s" custom format string. 
      format = "%s";
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 null, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);
   }
}
// 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
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 
    
    // Parse hour:minute:second value with "g" specifier.
    let intervalString = "17:14:48"
    let format = "g"
    let culture = CultureInfo.InvariantCulture
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->
        printfn $"Unable to parse '{intervalString}' using format {format}" 
    
    // Parse hours:minute.second value with custom format specifier.     
    let intervalString = "17:14:48.153"
    let format = @"h\:mm\:ss\.fff"
    let culture = null
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->
        printfn $"Unable to parse '{intervalString}' using format {format}"    

    // 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
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}"    
        
    // 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
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 
    
    // 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")
    match TimeSpan.TryParseExact(intervalString, format, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 

    // Parse a single number using the "c" standard format string. 
    let intervalString = "12"
    let format = "c"
    match TimeSpan.TryParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 
    
    // Parse a single number using the "%h" custom format string. 
    let format = "%h"
    match TimeSpan.TryParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 
    
    // Parse a single number using the "%s" custom format string. 
    let format = "%s"
    match TimeSpan.TryParseExact(intervalString, format, null, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"'{intervalString}' ({format}) --> {interval}"
    | _ ->   
        printfn $"Unable to parse '{intervalString}' using format {format}" 
// 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
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If
      
      ' Parse hour:minute:second value with "g" specifier.
      intervalString = "17:14:48"
      format = "g"
      culture = CultureInfo.InvariantCulture
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If
      
      ' Parse hours:minute.second value with custom format specifier.     
      intervalString = "17:14:48.153"
      format = "h\:mm\:ss\.fff"
      culture = Nothing
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 

      ' 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
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 
            
      ' 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
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 
      
      ' 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")
      If TimeSpan.TryParseExact(intervalString, format, 
                                culture, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)
      End If 

      ' Parse a single number using the "c" standard format string. 
      intervalString = "12"
      format = "c"
      If TimeSpan.TryParseExact(intervalString, format, 
                                Nothing, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 
      
      ' Parse a single number using the "%h" custom format string. 
      format = "%h"
      If TimeSpan.TryParseExact(intervalString, format, 
                                Nothing, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 
      
      ' Parse a single number using the "%s" custom format string. 
      format = "%s"
      If TimeSpan.TryParseExact(intervalString, format, 
                                Nothing, TimeSpanStyles.AssumeNegative, interval) Then
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval)
      Else
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format)   
      End If 
   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 TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) metodo analizza la rappresentazione di stringa di un intervallo di tempo, che deve essere nel formato definito dal format parametro , ad eccezione del fatto che i caratteri iniziali e finali degli spazi vuoti vengono ignorati. Questo metodo è simile al metodo , ad eccezione del ParseExact(String, String, IFormatProvider, TimeSpanStyles) fatto che non genera un'eccezione se la conversione non riesce.

Il format parametro è una stringa che contiene 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 personalizzate.

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 utilizzato 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 un intervallo di tempo negativo solo se è presente un segno negativo (TimeSpanStyles.None) o se viene sempre interpretato come un 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

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

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

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

public:
 static bool TryParseExact(ReadOnlySpan<char> input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
static member TryParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.TimeSpanStyles * TimeSpan -> bool
Public Shared Function TryParseExact (input As ReadOnlySpan(Of Char), formats As String(), formatProvider As IFormatProvider, styles As TimeSpanStyles, ByRef result As TimeSpan) As Boolean

Parametri

input
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano un intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe di formato standard o personalizzato che definiscono i formati accettabili di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Uno o più valori di enumerazione che indicano lo stile di input.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParseExact(String, String[], IFormatProvider, TimeSpan)

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

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

public:
 static bool TryParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result);
public static bool TryParseExact (string? input, string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParseExact (string? input, string[] formats, IFormatProvider? formatProvider, out TimeSpan result);
static member TryParseExact : string * string[] * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParseExact (input As String, formats As String(), formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe di formato standard o personalizzato che definiscono i formati accettabili di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene chiamato il TryParseExact(String, String[], IFormatProvider, TimeSpan) 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 il numero di giorni in un intervallo di tempo. La stringa di formato personalizzata viene invece %h usata per interpretare una singola cifra come numero di ore. Per rendere effettiva questa modifica, si noti 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) {
         if(TimeSpan.TryParseExact(input, formats, culture, out interval))
            Console.WriteLine("{0} --> {1:c}", input, interval);
         else
            Console.WriteLine("Unable to parse {0}", input);   
      }
   }
}
// The example displays the following output:
//       3 --> 03:00:00
//       16:42 --> 16:42:00
//       Unable to parse 1:6:52:35.0625
//       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
    match TimeSpan.TryParseExact(input, formats, culture) with
    | true, interval ->
        printfn $"{input} --> {interval:c}"
    | _ ->
        printfn $"Unable to parse {input}"
// The example displays the following output:
//       3 --> 03:00:00
//       16:42 --> 16:42:00
//       Unable to parse 1:6:52:35.0625
//       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
         If TimeSpan.TryParseExact(input, formats, culture, interval) Then
            Console.WriteLine("{0} --> {1:c}", input, interval)   
         Else
            Console.WriteLine("Unable to parse {0}", input)   
         End If            
      Next
   End Sub
End Module
' The example displays the following output:
'       3 --> 03:00:00
'       16:42 --> 16:42:00
'       Unable to parse 1:6:52:35.0625
'       1:6:52:35,0625 --> 1.06:52:35.0625000

Commenti

Il TryParseExact(String, String[], IFormatProvider, TimeSpan) metodo analizza la rappresentazione di stringa di un intervallo di tempo, che deve essere nel formato definito da una delle stringhe di formato specificate dal formats parametro , ad eccezione del fatto che gli spazi vuoti iniziali e finali vengono ignorati. Questo metodo è simile al metodo , ad eccezione del ParseExact(String, String[], IFormatProvider) fatto che non genera un'eccezione se la conversione non riesce.

Il formats parametro è una matrice di stringhe i cui elementi sono costituiti da un singolo identificatore di formato standard o da 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 personalizzate. 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 TryParseExact 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

TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan)

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

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

public:
 static bool TryParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, System::Globalization::TimeSpanStyles styles, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (string input, string[] formats, IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (string? input, string?[]? formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
public static bool TryParseExact (string? input, string[] formats, IFormatProvider? formatProvider, System.Globalization.TimeSpanStyles styles, out TimeSpan result);
static member TryParseExact : string * string[] * IFormatProvider * System.Globalization.TimeSpanStyles * TimeSpan -> bool
Public Shared Function TryParseExact (input As String, formats As String(), formatProvider As IFormatProvider, styles As TimeSpanStyles, ByRef result As TimeSpan) As Boolean

Parametri

input
String

Stringa che specifica l'intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe di formato standard o personalizzato che definiscono i formati accettabili di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

styles
TimeSpanStyles

Uno o più valori di enumerazione che indicano lo stile di input.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene chiamato il TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) 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("fr-FR");
      
      // Parse each string in inputs using formats and the fr-FR culture.
      foreach (string input in inputs) {
         if(TimeSpan.TryParseExact(input, formats, culture, 
                                   TimeSpanStyles.AssumeNegative, out interval))
            Console.WriteLine("{0} --> {1:c}", input, interval);
         else
            Console.WriteLine("Unable to parse {0}", input);   
      }
   }
}
// The example displays the following output:
//       3 --> -03:00:00
//       16:42 --> 16:42:00
//       Unable to parse 1:6:52:35.0625
//       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 "fr-FR"

// Parse each string in inputs using formats and the fr-FR culture.
for input in inputs do
    match TimeSpan.TryParseExact(input, formats, culture, TimeSpanStyles.AssumeNegative) with
    | true, interval ->
        printfn $"{input} --> {interval:c}"
    | _ ->
        printfn $"Unable to parse {input}"
// The example displays the following output:
//       3 --> -03:00:00
//       16:42 --> 16:42:00
//       Unable to parse 1:6:52:35.0625
//       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 fr-FR culture.
      For Each input As String In inputs
         If TimeSpan.TryParseExact(input, formats, culture, 
                                   TimeSpanStyles.AssumeNegative, interval) Then
            Console.WriteLine("{0} --> {1:c}", input, interval)   
         Else
            Console.WriteLine("Unable to parse {0}", input)   
         End If            
      Next
   End Sub
End Module
' The example displays the following output:
'       3 --> -03:00:00
'       16:42 --> 16:42:00
'       Unable to parse 1:6:52:35.0625
'       1:6:52:35,0625 --> 1.06:52:35.0625000

Commenti

Il TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) metodo analizza la rappresentazione stringa di un intervallo di tempo, che deve essere nel formato definito da una delle stringhe di formato specificate dal formats parametro, ad eccezione del fatto che i caratteri di spazi vuoti iniziali e finali vengono ignorati. Questo metodo è simile al metodo, ad eccezione del fatto che non genera un'eccezione ParseExact(String, String[], IFormatProvider, TimeSpanStyles) se la conversione ha esito negativo.

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

TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpan)

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

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

public:
 static bool TryParseExact(ReadOnlySpan<char> input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, out TimeSpan result);
static member TryParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParseExact (input As ReadOnlySpan(Of Char), formats As String(), formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

Parametri

input
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano un intervallo di tempo da convertire.

formats
String[]

Matrice di stringhe di formato standard o personalizzato che definiscono i formati accettabili di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

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

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

public:
 static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, out TimeSpan result);
static member TryParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParseExact (input As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

Parametri

input
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano un intervallo di tempo da convertire.

format
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano una stringa di formato standard o personalizzato che definisce il formato accettabile di input.

formatProvider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParseExact(String, String, IFormatProvider, TimeSpan)

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 bool TryParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider, [Runtime::InteropServices::Out] TimeSpan % result);
public static bool TryParseExact (string input, string format, IFormatProvider formatProvider, out TimeSpan result);
public static bool TryParseExact (string? input, string? format, IFormatProvider? formatProvider, out TimeSpan result);
public static bool TryParseExact (string? input, string format, IFormatProvider? formatProvider, out TimeSpan result);
static member TryParseExact : string * string * IFormatProvider * TimeSpan -> bool
Public Shared Function TryParseExact (input As String, format As String, formatProvider As IFormatProvider, ByRef result As TimeSpan) As Boolean

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.

result
TimeSpan

Quando questo metodo viene restituito, contiene un oggetto che rappresenta l'intervallo di tempo specificato da input o Zero in caso di conversione non riuscita. Questo parametro viene passato non inizializzato.

Restituisce

true se input è stato convertito correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene usato il TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) 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;
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
      
      // Parse hour:minute:second value with "G" specifier.
      intervalString = "17:14:48";
      format = "G";
      culture = CultureInfo.InvariantCulture;
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
      
      // Parse hours:minute.second value with "G" specifier 
      // and current (en-US) culture.     
      intervalString = "17:14:48.153";
      format = "G";
      culture = CultureInfo.CurrentCulture;
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", 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;
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", 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");
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
      
      // Parse days:hours:minute.second value with "G" specifier 
      // and fr-FR culture.     
      intervalString = "3:17:14:48,153";
      format = "G";
      if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);

      // Parse a single number using the "c" standard format string. 
      intervalString = "12";
      format = "c";
      if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
      
      // Parse a single number using the "%h" custom format string. 
      format = "%h";
      if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
      
      // Parse a single number using the "%s" custom format string. 
      format = "%s";
      if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      else
         Console.WriteLine("Unable to parse {0}", intervalString);
   }
}
// The example displays the following output:
//       '17:14' --> 17:14:00
//       Unable to parse 17:14:48
//       Unable to parse 17:14:48.153
//       '3:17:14:48.153' --> 3.17:14:48.1530000
//       Unable to parse 3:17:14:48.153
//       '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
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
    
    // Parse hour:minute:second value with "G" specifier.
    let intervalString = "17:14:48"
    let format = "G"
    let culture = CultureInfo.InvariantCulture
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
    
    // 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
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"

    // 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
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
        
    // 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")
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
    
    // Parse days:hours:minute.second value with "G" specifier 
    // and fr-FR culture.     
    let intervalString = "3:17:14:48,153"
    let format = "G"
    match TimeSpan.TryParseExact(intervalString, format, culture) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"

    // Parse a single number using the "c" standard format string. 
    let intervalString = "12"
    let format = "c"
    match TimeSpan.TryParseExact(intervalString, format, null) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
    
    // Parse a single number using the "%h" custom format string. 
    let format = "%h"
    match TimeSpan.TryParseExact(intervalString, format, null) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
    
    // Parse a single number using the "%s" custom format string. 
    let format = "%s"
    match TimeSpan.TryParseExact(intervalString, format, null) with
    | true, interval ->
        printfn $"'{intervalString}' --> {interval}"
    | _ ->
        printfn $"Unable to parse {intervalString}"
// The example displays the following output:
//       '17:14' --> 17:14:00
//       Unable to parse 17:14:48
//       Unable to parse 17:14:48.153
//       '3:17:14:48.153' --> 3.17:14:48.1530000
//       Unable to parse 3:17:14:48.153
//       '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
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
      
      ' Parse hour:minute:second value with "G" specifier.
      intervalString = "17:14:48"
      format = "G"
      culture = CultureInfo.InvariantCulture
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If

      ' Parse hours:minute.second value with "G" specifier 
      ' and current (en-US) culture.     
      intervalString = "17:14:48.153"
      format = "G"
      culture = CultureInfo.CurrentCulture
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If

      ' 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
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
            
      ' 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")
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
      
      ' 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")
      If TimeSpan.TryParseExact(intervalString, format, culture, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If

      ' Parse a single number using the "c" standard format string. 
      intervalString = "12"
      format = "c"
      If TimeSpan.TryParseExact(intervalString, format, Nothing, interval)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
      
      ' Parse a single number using the "%h" custom format string. 
      format = "%h"
      If TimeSpan.TryParseExact(intervalString, format, Nothing, interval)
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
      
      ' Parse a single number using the "%s" custom format string. 
      format = "%s"
      If TimeSpan.TryParseExact(intervalString, format, Nothing, interval) Then
         Console.WriteLine("'{0}' --> {1}", intervalString, interval)
      Else
         Console.WriteLine("Unable to parse {0}", intervalString)
      End If
   End Sub
End Module
' The example displays the following output:
'       '17:14' --> 17:14:00
'       Unable to parse 17:14:48
'       Unable to parse 17:14:48.153
'       '3:17:14:48.153' --> 3.17:14:48.1530000
'       Unable to parse 3:17:14:48.153
'       '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 TryParseExact(String, String, IFormatProvider, TimeSpan) 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. Questo metodo è simile al metodo, ad eccezione del fatto che non genera un'eccezione ParseExact(String, String, IFormatProvider) se la conversione ha esito negativo.

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 TryParseExact(String, String, IFormatProvider, TimeSpan) 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