DateTime.TryParseExact 方法

定義

將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match a specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

多載

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

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

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the specified char span of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定格式。The format of the string representation must match at least one of the specified formats exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 Prepare your application for the Japanese era change (讓應用程式準備好因應日本紀元變更)。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 請參閱使用紀年以了解 .NET 中支援使用多種紀年的日曆,以及在處理支援多種紀年的日曆時能採用最佳做法。See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles * DateTime -> bool
Public Shared Function TryParseExact (s As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

參數

s
ReadOnlySpan<Char>

包含字元的範圍,其表示要轉換的日期和時間。A span containing the characters representing a date and time to convert.

format
ReadOnlySpan<Char>

s 的必要格式。The required format of s.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

style
DateTimeStyles

一個或多個列舉值的位元組合,表示 s 的允許格式。A bitwise combination of one or more enumeration values that indicate the permitted format of s.

result
DateTime

如果轉換成功,這個方法會傳回包含與 DateTime 中內含之日期與時間相等的 s 值;如果轉換失敗,則為 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 sformat 參數為 null、空字串,或不包含與 format 中指定之模式相對應的日期和時間,則此轉換作業會失敗。The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date and time that correspond to the pattern specified in format. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

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

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the specified char span of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(ReadOnlySpan<char> s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (ReadOnlySpan<char> s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.DateTimeStyles * DateTime -> bool
Public Shared Function TryParseExact (s As ReadOnlySpan(Of Char), formats As String(), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

參數

s
ReadOnlySpan<Char>

包含所要剖析字串的範圍。The span containing the string to parse.

formats
String[]

s 允許的格式陣列。An array of allowable formats of s.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

style
DateTimeStyles

列舉值的位元組合,這個組合會定義如何根據目前時區或目前日期解譯已剖析的日期。A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. 一般會指定的值是 NoneA typical value to specify is None.

result
DateTime

如果轉換成功,這個方法會傳回包含與 DateTime 中內含之日期與時間相等的 s 值;如果轉換失敗,則為 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 s 參數為 nullEmpty,或不包含日期和時間的有效字串表示,則轉換會失敗。The conversion fails if the s parameter is null, is Empty, or does not contain a valid string representation of a date and time. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 true 參數轉換成功,則為 s,否則為 falsetrue if the s parameter was converted successfully; otherwise, false.

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(System::String ^ s, System::String ^ format, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : string * string * IFormatProvider * System.Globalization.DateTimeStyles * DateTime -> bool
Public Shared Function TryParseExact (s As String, format As String, provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

參數

s
String

字串,含有要轉換的日期和時間。A string containing a date and time to convert.

format
String

s 的必要格式。The required format of s.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

style
DateTimeStyles

一個或多個列舉值的位元組合,表示 s 的允許格式。A bitwise combination of one or more enumeration values that indicate the permitted format of s.

result
DateTime

如果轉換成功,這個方法會傳回包含與 DateTime 中內含之日期與時間相等的 s 值;如果轉換失敗,則為 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 sformat 參數為 null、空字串,或不包含與 format 中指定之模式相對應的日期和時間,則此轉換作業會失敗。The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date and time that correspond to the pattern specified in format. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

例外狀況

styles 不是有效的 DateTimeStyles 值。styles is not a valid DateTimeStyles value.

-或--or- styles 包含 DateTimeStyles 值的無效組合 (例如,AssumeLocalAssumeUniversal)。styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

範例

下列範例示範 DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 方法。The following example demonstrates the DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method. 請注意,當 styles 參數等於 DateTimeStyles.None 時,無法成功剖析字串 "5/01/2009 8:30 AM",因為 format不允許開頭的空格。Note that the string " 5/01/2009 8:30 AM" cannot be parsed successfully when the styles parameter equals DateTimeStyles.None because leading spaces are not allowed by format. 此外,無法以 "MM/dd/yyyyhh: MM" 的 format 成功剖析字串 "5/01/2009 09:00",因為在 format 需要的情況下,日期字串不會在月份號碼前面加上零。Additionally, the string "5/01/2009 09:00" cannot be parsed successfully with a format of "MM/dd/yyyyhh:mm" because the date string does not precede the month number with a leading zero, as format requires.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo enUS = new CultureInfo("en-US"); 
      string dateString;
      DateTime dateValue;
      
      // Parse date with no style flags.
      dateString = " 5/01/2009 8:30 AM";
      if (DateTime.TryParseExact(dateString, "g", enUS, 
                                 DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      // Allow a leading space in the date string.
      if (DateTime.TryParseExact(dateString, "g", enUS, 
                                 DateTimeStyles.AllowLeadingWhite, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      
      // Use custom formats with M and MM.
      dateString = "5/01/2009 09:00";
      if (DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, 
                                 DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      // Allow a leading space in the date string.
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, 
                              DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      // Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00"; 
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, 
                              DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      // Allow a leading space in the date string.
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, 
                              DateTimeStyles.AdjustToUniversal, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
           
      // Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z";
      if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                     DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                 DateTimeStyles.RoundtripKind, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

   }
}
// The example displays the following output:
//    ' 5/01/2009 8:30 AM' is not in an acceptable format.
//    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
//    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
//    '5/01/2009 09:00' is not in an acceptable format.
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim enUS As New CultureInfo("en-US") 
      Dim dateString As String
      Dim dateValue As Date
      
      ' Parse date with no style flags.
      dateString = " 5/01/2009 8:30 AM"
      If Date.TryParseExact(dateString, "g", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "g", enUS, _
                            DateTimeStyles.AllowLeadingWhite, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      
      ' Use custom formats with M and MM.
      dateString = "5/01/2009 09:00"
      If Date.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If

      ' Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00" 
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                            DateTimeStyles.AdjustToUniversal, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
           
      ' Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z"
      If Date.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                                     DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      
      If Date.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                            DateTimeStyles.RoundtripKind, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
   End Sub
End Module
' The example displays the following output:
'    ' 5/01/2009 8:30 AM' is not in an acceptable format.
'    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
'    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
'    '5/01/2009 09:00' is not in an acceptable format.
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).

備註

DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 方法會剖析日期的字串表示,其必須是由 format 參數所定義的格式。The DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method parses the string representation of a date, which must be in the format defined by the format parameter. 它類似于 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) 方法,不同之處在于如果轉換失敗,TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 方法不會擲回例外狀況。It is similar to the DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method, except that the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method does not throw an exception if the conversion fails.

s 參數包含要剖析的日期和時間,而且必須是由 format 參數所定義的格式。The s parameter contains the date and time to parse and must be in a format defined by the format parameter. 如果日期、時間和時區元素出現在 s中,它們也必須以 format所指定的順序顯示。If date, time, and time zone elements are present in s, they must also appear in the order specified by format. 如果 format 定義沒有時間元素的日期,且剖析作業成功,則產生的 DateTime 值會有午夜的時間(00:00:00)。If format defines a date with no time element and the parse operation succeeds, the resulting DateTime value has a time of midnight (00:00:00). 如果 format 定義的時間沒有日期元素,且剖析作業成功,則產生的 DateTime 值預設會有 DateTime.Now.Date的日期,或如果 styles 包含 DateTimeStyles.NoCurrentDateDefault 旗標,則會有 DateTime.MinValue.Date 的日期。If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value by default has a date of DateTime.Now.Date, or it has a date of DateTime.MinValue.Date if styles includes the DateTimeStyles.NoCurrentDateDefault flag. style 參數會決定 s 參數是否可以包含前置、內部或尾端的空白字元。The style parameter determines whether the s parameter can contain leading, inner, or trailing white space characters.

如果 s 未包含時區資訊,則會 DateTimeKind.Unspecified所傳回 DateTime 物件的 Kind 屬性。If s contains no time zone information, the Kind property of the returned DateTime object is DateTimeKind.Unspecified. 您可以使用 DateTimeStyles.AssumeLocal 旗標來變更此行為,這會傳回其 Kind 屬性 DateTimeKind.LocalDateTime 值,或使用 DateTimeStyles.AssumeUniversalDateTimeStyles.AdjustToUniversal 旗標來傳回 DateTime 屬性 KindDateTimeKind.Utc值。This behavior can be changed by using the DateTimeStyles.AssumeLocal flag, which returns a DateTime value whose Kind property is DateTimeKind.Local, or by using the DateTimeStyles.AssumeUniversal and DateTimeStyles.AdjustToUniversal flags, which returns a DateTime value whose Kind property is DateTimeKind.Utc. 如果包含時區資訊,則會在必要時將時間轉換為本地時間,而傳回之 DateTime 物件的 Kind 屬性會設定為 [DateTimeKind.Local]。If s contains time zone information, the time is converted to local time, if necessary, and the Kind property of the returned DateTime object is set to DateTimeKind.Local. 您可以使用 DateTimeStyles.RoundtripKind 旗標來變更此行為,不要將國際標準時間(UTC)轉換為當地時間,並將 Kind 屬性設定為 [DateTimeKind.Utc]。This behavior can be changed by using the DateTimeStyles.RoundtripKind flag to not convert Coordinated Universal Time (UTC) to a local time and set the Kind property to DateTimeKind.Utc.

format 參數所包含的模式會對應到 s 參數的預期格式。The format parameter contains a pattern that corresponds to the expected format of the s parameter. format 參數中的模式是由自訂日期和時間格式字串資料表中的一或多個自訂格式規範所組成,或是從標準日期和時間格式字串資料表中識別預先定義模式的單一標準格式指定名稱。The pattern in the format parameter consists of one or more custom format specifiers from the Custom Date and Time Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard Date and Time Format Strings table.

如果您未在自訂格式模式中使用日期或時間分隔符號,請使用 provider 參數的不因文化特性,以及每個自訂格式規範的最寬形式。If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. 例如,如果您想要在模式中指定小時,請指定較寬的格式 "HH",而不是較窄的格式 "H"。For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H".

注意

您可以呼叫 DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) 方法並指定多個允許的格式,而不是要求 s 必須符合單一格式,才能成功進行剖析作業。Rather than requiring that s conform to a single format for the parse operation to succeed, you can call the DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method and specify multiple permitted formats. 這讓剖析作業更可能成功。This makes the parse operation more likely to succeed.

s 中使用的特定日期和時間符號和字串(例如特定語言的星期幾名稱)是由 provider 參數所定義,如果 format 是標準格式規範字符串,則是 s 的精確格式。The particular date and time symbols and strings (such as the names of the days of the week in a particular language) used in s are defined by the provider parameter, as is the precise format of s if format is a standard format specifier string. provider 參數可以是下列任何一項:The provider parameter can be any of the following:

如果 null``provider,則會使用對應至目前文化特性的 CultureInfo 物件。If provider is null, the CultureInfo object that corresponds to the current culture is used.

styles 參數包含 DateTimeStyles 列舉的一或多個成員,可決定是否在 s 中出現不是由 format 定義的空白字元,以及控制剖析作業的精確行為。The styles parameter includes one or more members of the DateTimeStyles enumeration that determine whether and where white space not defined by format can appear in s and that control the precise behavior of the parse operation. 下表描述 DateTimeStyles 列舉的每個成員如何影響 TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 方法的作業。The following table describes how each member of the DateTimeStyles enumeration affects the operation of the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method.

DateTimeStyles 成員DateTimeStyles member 說明Description
AdjustToUniversal 剖析 s,並在必要時將它轉換為 UTC。Parses s and, if necessary, converts it to UTC. 如果 s 包含時區時差,或 s 不包含時區資訊,但 styles 包含 DateTimeStyles.AssumeLocal 旗標,則方法會剖析字串、呼叫 ToUniversalTime 以將傳回的 DateTime 值轉換成 UTC,並將 Kind 屬性設定為 DateTimeKind.UtcIf s includes a time zone offset, or if s contains no time zone information but styles includes the DateTimeStyles.AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind.Utc. 如果 s 表示它代表 UTC,或者 s 不包含時區資訊,但 styles 包含 DateTimeStyles.AssumeUniversal 旗標,則方法會剖析字串,並在傳回的 DateTime 值上不執行時區轉換,並將 Kind 屬性設定為 DateTimeKind.UtcIf s indicates that it represents UTC, or if s does not contain time zone information but styles includes the DateTimeStyles.AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind.Utc. 在所有其他情況下,旗標沒有任何作用。In all other cases, the flag has no effect.
AllowInnerWhite 指定不是由 format 定義的空白字元可以出現在任何個別的日期或時間元素之間。Specifies that white space not defined by format can appear between any individual date or time element.
AllowLeadingWhite 指定不是由 format 定義的空白字元會出現在 s開頭。Specifies that white space not defined by format can appear at the beginning of s.
AllowTrailingWhite 指定不是由 format 定義的空白字元會出現在 s的結尾。Specifies that white space not defined by format can appear at the end of s.
AllowWhiteSpaces 指定 s 可能包含不是由 format定義的前置、內部和尾端空白字元。Specifies that s may contain leading, inner, and trailing white spaces not defined by format.
AssumeLocal 指定如果 s 缺少任何時區資訊,則會假設為代表當地時間。Specifies that if s lacks any time zone information, it is assumed to represent a local time. 除非出現 DateTimeStyles.AdjustToUniversal 旗標,否則傳回的 DateTime 值的 Kind 屬性會設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.
AssumeUniversal 指定如果 s 缺少任何時區資訊,則會假設為代表 UTC。Specifies that if s lacks any time zone information, it is assumed to represent UTC. 除非出現 DateTimeStyles.AdjustToUniversal 旗標,否則方法會將傳回的 DateTime 值從 UTC 轉換為當地時間,並將其 Kind 屬性設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.
NoCurrentDateDefault 如果 s 包含沒有日期資訊的時間,則傳回值的日期會設定為 DateTime.MinValue.DateIf s contains time without date information, the date of the return value is set to DateTime.MinValue.Date.
None s 參數會使用預設值進行剖析。The s parameter is parsed using default values. 不允許出現在 format 中的空白字元。No white space other than that present in format is allowed. 如果 s 缺少日期元件,則傳回的 DateTime 值的日期會設定為1/1/0001。If s lacks a date component, the date of the returned DateTime value is set to 1/1/0001. 如果 s 未包含時區資訊,則傳回之 DateTime 物件的 Kind 屬性會設定為 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is set to DateTimeKind.Unspecified. 如果 s中出現時區資訊,則會將時間轉換為本地時間,而傳回之 DateTime 物件的 Kind 屬性會設定為 [DateTimeKind.Local]。If time zone information is present in s, the time is converted to local time and the Kind property of the returned DateTime object is set to DateTimeKind.Local.
RoundtripKind 對於包含時區資訊的字串,會嘗試防止轉換成 DateTime 值,並將其 Kind 屬性設定為 DateTimeKind.LocalFor strings that contain time zone information, tries to prevent the conversion to a DateTime value with its Kind property set to DateTimeKind.Local. 此旗標主要會防止 UTC 時間轉換成當地時間。This flag primarily prevents the conversion of UTC times to local times.

給呼叫者的注意事項

.NET Framework 4.NET Framework 4中,如果要剖析的字串包含小時元件以及不在協定中的 AM/PM 指示項,則 TryParseExact 方法會傳回 falseIn the .NET Framework 4.NET Framework 4, the TryParseExact method returns false if the string to be parsed contains an hour component and an AM/PM designator that are not in agreement. .NET Framework 3.5.NET Framework 3.5 和較早的版本中,會忽略 AM/PM 指示項。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, the AM/PM designator is ignored.

另請參閱

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定格式。The format of the string representation must match at least one of the specified formats exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(System::String ^ s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (string s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles * DateTime -> bool
Public Shared Function TryParseExact (s As String, formats As String(), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

參數

s
String

字串,包含要轉換的日期和時間。A string that contains a date and time to convert.

formats
String[]

s 允許的格式陣列。An array of allowable formats of s.

provider
IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。An object that supplies culture-specific format information about s.

style
DateTimeStyles

列舉值的位元組合,表示 s 所允許的格式。A bitwise combination of enumeration values that indicates the permitted format of s. 一般會指定的值是 NoneA typical value to specify is None.

result
DateTime

如果轉換成功,這個方法會傳回包含與 DateTime 中內含之日期與時間相等的 s 值;如果轉換失敗,則為 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 sformatsnullsformats 的一個項目為空字串,或是 s 的格式沒有與 formats 中的至少一個格式模式所指定的內容完全相同,則此轉換作業會失敗。The conversion fails if s or formats is null, s or an element of formats is an empty string, or the format of s is not exactly as specified by at least one of the format patterns in formats. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 true 參數轉換成功,則為 s,否則為 falsetrue if the s parameter was converted successfully; otherwise, false.

例外狀況

styles 不是有效的 DateTimeStyles 值。styles is not a valid DateTimeStyles value.

-或--or- styles 包含 DateTimeStyles 值的無效組合 (例如,AssumeLocalAssumeUniversal)。styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

範例

下列範例會使用 DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 方法,以確保可以成功剖析數種可能格式的字串。The following example uses the DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method to ensure that a string in a number of possible formats can be successfully parsed .

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                         "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                         "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                         "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                         "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
      string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                              "5/1/2009 6:32:00", "05/01/2009 06:32", 
                              "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
      DateTime dateValue;
      
      foreach (string dateString in dateStrings)
      {
         if (DateTime.TryParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
                                    DateTimeStyles.None, 
                                    out dateValue))
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
         else
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
      }
   }
}
// The example displays the following output:
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim formats() As String = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", _
                                 "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", _
                                 "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", _
                                 "M/d/yyyy h:mm", "M/d/yyyy h:mm", _
                                 "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"}
      Dim dateStrings() As String = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", _
                                     "5/1/2009 6:32:00", "05/01/2009 06:32", _
                                     "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"} 

      Dim dateValue As DateTime
      
      For Each dateString As String In dateStrings
         If Date.TryParseExact(dateString, formats, _
                               New CultureInfo("en-US"), _
                               DateTimeStyles.None, _
                               dateValue) Then
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue)
         Else
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString)
         End If                                               
      Next
   End Sub   
End Module
' The example displays the following output:
'       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
'       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

備註

DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) 方法會剖析符合指派給 formats 參數之任何一種模式之日期的字串表示。The DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method parses the string representation of a date that matches any one of the patterns assigned to the formats parameter. 它就像是 DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 方法,但如果轉換失敗,TryParseExact 方法不會擲回例外狀況。It is like the DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) method, except the TryParseExact method does not throw an exception if the conversion fails.

s 參數包含要剖析的日期和時間。The s parameter contains the date and time to parse. 如果 s 參數只包含時間且沒有日期,則會使用目前的日期,除非 style 參數包含 DateTimeStyles.NoCurrentDateDefault 旗標,在此情況下會使用預設日期(DateTime.Date.MinValue)。If the s parameter contains only a time and no date, the current date is used unless the style parameter includes the DateTimeStyles.NoCurrentDateDefault flag, in which case the default date (DateTime.Date.MinValue) is used. 如果 s 參數只包含日期,而且沒有時間,則會使用午夜(00:00:00)。If the s parameter contains only a date and no time, midnight (00:00:00) is used. style 參數也會決定 s 參數是否可以包含前置、內部或尾端空白字元,而不是 formats中的其中一個格式字串所允許的空白字元。The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters other than those permitted by one of the format strings in formats.

如果 s 未包含時區資訊,則會 DateTimeKind.Unspecified所傳回 DateTime 物件的 Kind 屬性。If s contains no time zone information, the Kind property of the returned DateTime object is DateTimeKind.Unspecified. 您可以使用 DateTimeStyles.AssumeLocal 旗標來變更此行為,這會傳回其 Kind 屬性 DateTimeKind.LocalDateTime 值,或使用 DateTimeStyles.AssumeUniversalDateTimeStyles.AdjustToUniversal 旗標來傳回 DateTime 屬性 KindDateTimeKind.Utc值。This behavior can be changed by using the DateTimeStyles.AssumeLocal flag, which returns a DateTime value whose Kind property is DateTimeKind.Local, or by using the DateTimeStyles.AssumeUniversal and DateTimeStyles.AdjustToUniversal flags, which returns a DateTime value whose Kind property is DateTimeKind.Utc. 如果包含時區資訊,則會在必要時將時間轉換為本地時間,而傳回之 DateTime 物件的 Kind 屬性會設定為 [DateTimeKind.Local]。If s contains time zone information, the time is converted to local time, if necessary, and the Kind property of the returned DateTime object is set to DateTimeKind.Local. 您可以使用 DateTimeStyles.RoundtripKind 旗標來變更此行為,不要將國際標準時間(UTC)轉換為當地時間,並將 Kind 屬性設定為 [DateTimeKind.Utc]。This behavior can be changed by using the DateTimeStyles.RoundtripKind flag to not convert Coordinated Universal Time (UTC) to a local time and set the Kind property to DateTimeKind.Utc.

formats 參數包含模式陣列,其中一個 s 必須完全符合,才能成功剖析作業。The formats parameter contains an array of patterns, one of which s must match exactly if the parse operation is to succeed. formats 參數中的模式是由自訂日期和時間格式字串資料表中的一或多個自訂格式規範所組成,或是從標準日期和時間格式字串資料表中識別預先定義模式的單一標準格式指定名稱。The patterns in the formats parameter consist of one or more custom format specifiers from the Custom Date and Time Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard Date and Time Format Strings table.

如果您未在自訂格式模式中使用日期或時間分隔符號,請使用 provider 參數的不因文化特性,以及每個自訂格式規範的最寬形式。If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. 例如,如果您想要在模式中指定小時,請指定較寬的格式 "HH",而不是較窄的格式 "H"。For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H".

s 中使用的特定日期和時間符號和字串(例如特定語言的星期幾名稱)是由 provider 參數所定義,如果 format 是標準格式規範字符串,則是 s 的精確格式。The particular date and time symbols and strings (such as the names of the days of the week in a particular language) used in s are defined by the provider parameter, as is the precise format of s if format is a standard format specifier string. provider 參數可以是下列任何一項:The provider parameter can be any of the following:

如果 null``provider,則會使用對應至目前文化特性的 CultureInfo 物件。If provider is null, the CultureInfo object that corresponds to the current culture is used.

styles 參數包含 DateTimeStyles 列舉的一或多個成員,可決定是否在 s 中出現不是由 format 定義的空白字元,以及控制剖析作業的精確行為。The styles parameter includes one or more members of the DateTimeStyles enumeration that determine whether and where white space not defined by format can appear in s and that control the precise behavior of the parse operation. 下表描述 DateTimeStyles 列舉的每個成員如何影響 TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) 方法的作業。The following table describes how each member of the DateTimeStyles enumeration affects the operation of the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method.

DateTimeStyles 成員DateTimeStyles member 說明Description
AdjustToUniversal 剖析 s,並在必要時將它轉換為 UTC。Parses s and, if necessary, converts it to UTC. 如果 s 包含時區時差,或 s 不包含時區資訊,但 styles 包含 DateTimeStyles.AssumeLocal 旗標,則方法會剖析字串、呼叫 ToUniversalTime 以將傳回的 DateTime 值轉換成 UTC,並將 Kind 屬性設定為 DateTimeKind.UtcIf s includes a time zone offset, or if s contains no time zone information but styles includes the DateTimeStyles.AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind.Utc. 如果 s 表示它代表 UTC,或者 s 不包含時區資訊,但 styles 包含 DateTimeStyles.AssumeUniversal 旗標,則方法會剖析字串,並在傳回的 DateTime 值上不執行時區轉換,並將 Kind 屬性設定為 DateTimeKind.UtcIf s indicates that it represents UTC, or if s does not contain time zone information but styles includes the DateTimeStyles.AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind.Utc. 在所有其他情況下,旗標沒有任何作用。In all other cases, the flag has no effect.
AllowInnerWhite 指定不是由 format 定義的空白字元可以出現在任何個別的日期或時間元素之間。Specifies that white space not defined by format can appear between any individual date or time element.
AllowLeadingWhite 指定不是由 format 定義的空白字元會出現在 s開頭。Specifies that white space not defined by format can appear at the beginning of s.
AllowTrailingWhite 指定不是由 format 定義的空白字元會出現在 s的結尾。Specifies that white space not defined by format can appear at the end of s.
AllowWhiteSpaces 指定 s 可能包含不是由 format定義的前置、內部和尾端空白字元。Specifies that s may contain leading, inner, and trailing white spaces not defined by format.
AssumeLocal 指定如果 s 缺少任何時區資訊,則會假設為代表當地時間。Specifies that if s lacks any time zone information, it is assumed to represent a local time. 除非出現 DateTimeStyles.AdjustToUniversal 旗標,否則傳回的 DateTime 值的 Kind 屬性會設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.
AssumeUniversal 指定如果 s 缺少任何時區資訊,則會假設為代表 UTC。Specifies that if s lacks any time zone information, it is assumed to represent UTC. 除非出現 DateTimeStyles.AdjustToUniversal 旗標,否則方法會將傳回的 DateTime 值從 UTC 轉換為當地時間,並將其 Kind 屬性設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.
NoCurrentDateDefault 如果 s 包含沒有日期資訊的時間,則傳回值的日期會設定為 DateTime.MinValue.DateIf s contains time without date information, the date of the return value is set to DateTime.MinValue.Date.
None s 參數會使用預設值進行剖析。The s parameter is parsed using default values. 不允許出現在 format 中的空白字元。No white space other than that present in format is allowed. 如果 s 缺少日期元件,則傳回的 DateTime 值的日期會設定為1/1/0001。If s lacks a date component, the date of the returned DateTime value is set to 1/1/0001. 如果 s 未包含時區資訊,則傳回之 DateTime 物件的 Kind 屬性會設定為 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is set to DateTimeKind.Unspecified. 如果 s中出現時區資訊,則會將時間轉換為本地時間,而傳回之 DateTime 物件的 Kind 屬性會設定為 [DateTimeKind.Local]。If time zone information is present in s, the time is converted to local time and the Kind property of the returned DateTime object is set to DateTimeKind.Local.
RoundtripKind 對於包含時區資訊的字串,會嘗試防止轉換成 DateTime 值,並將其 Kind 屬性設定為 DateTimeKind.LocalFor strings that contain time zone information, tries to prevent the conversion to a DateTime value with its Kind property set to DateTimeKind.Local. 此旗標主要會防止 UTC 時間轉換成當地時間。This flag primarily prevents the conversion of UTC times to local times.

給呼叫者的注意事項

.NET Framework 4.NET Framework 4中,如果要剖析的字串包含小時元件以及不在協定中的 AM/PM 指示項,則 TryParseExact 方法會傳回 falseIn the .NET Framework 4.NET Framework 4, the TryParseExact method returns false if the string to be parsed contains an hour component and an AM/PM designator that are not in agreement. .NET Framework 3.5.NET Framework 3.5 和較早的版本中,會忽略 AM/PM 指示項。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, the AM/PM designator is ignored.

另請參閱

適用於