DateTimeOffset.TryParseExact 方法

定義

將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffsetConverts the specified string representation of a date and time to its DateTimeOffset equivalent. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match a specified format exactly.

多載

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffsetConverts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須完全符合其中一個指定的格式。The format of the string representation must match one of the specified formats exactly.

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

使用指定的格式、文化特性特定格式資訊與樣式,將字元範圍內的日期和時間表示,轉換為其相等的 DateTimeOffsetConverts the representation of a date and time in a character span to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. 日期和時間表示的格式必須完全符合指定的格式。The format of the date and time representation must match the specified format exactly.

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

使用指定的格式、特定的文化特性格式資訊及樣式,將字元範圍中的日期和時間表示轉換為其對等的 DateTimeOffsetConverts the representation of a date and time in a character span to its DateTimeOffset equivalent using the specified formats, culture-specific format information, and style. 日期和時間表示的格式必須完全符合其中一個指定的格式。The format of the date and time representation must match one of the specified formats exactly.

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffsetConverts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly.

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffsetConverts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須完全符合其中一個指定的格式。The format of the string representation must match one of the specified formats exactly.

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

參數

input
String

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

formats
String[]

陣列,定義 input 的預期格式。An array that defines the expected formats of input.

formatProvider
IFormatProvider

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

styles
DateTimeStyles

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

result
DateTimeOffset

如果轉換成功,方法傳回時內含的 DateTimeOffset 就會和 input 的日期和時間相等;如果轉換失敗,則為 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. 如果 input 不包含日期和時間的有效字串表示,或者不包含 format 定義之預期格式的日期和時間,或者 formatsnull,則轉換會失敗。The conversion fails if the input does not contain a valid string representation of a date and time, or does not contain the date and time in the expected format defined by format, or if formats is null. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

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

例外狀況

styles 包含未定義的 DateTimeStyles 值。styles includes an undefined DateTimeStyles value.

-或--or- 不支援 NoCurrentDateDefaultNoCurrentDateDefault is not supported.

-或--or- styles 包含互斥的 DateTimeStyles 值。styles includes mutually exclusive DateTimeStyles values.

範例

下列範例會針對日期和時間和位移值的字串表示定義多個輸入格式,然後將使用者輸入的字串傳遞給 TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTimeOffset) 方法。The following example defines multiple input formats for the string representation of a date and time and offset value, and then passes the string that is entered by the user to the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTimeOffset) method.

 TextReader conIn = Console.In;
 TextWriter conOut = Console.Out;
 int tries = 0;
 string input = String.Empty;

 string[] formats = new string[] {"M/dd/yyyy HH:m zzz", "MM/dd/yyyy HH:m zzz", 
                                  "M/d/yyyy HH:m zzz", "MM/d/yyyy HH:m zzz", 
                                  "M/dd/yy HH:m zzz", "MM/dd/yy HH:m zzz", 
                                  "M/d/yy HH:m zzz", "MM/d/yy HH:m zzz",                                 
                                  "M/dd/yyyy H:m zzz", "MM/dd/yyyy H:m zzz", 
                                  "M/d/yyyy H:m zzz", "MM/d/yyyy H:m zzz", 
                                  "M/dd/yy H:m zzz", "MM/dd/yy H:m zzz", 
                                  "M/d/yy H:m zzz", "MM/d/yy H:m zzz",                               
                                  "M/dd/yyyy HH:mm zzz", "MM/dd/yyyy HH:mm zzz", 
                                  "M/d/yyyy HH:mm zzz", "MM/d/yyyy HH:mm zzz", 
                                  "M/dd/yy HH:mm zzz", "MM/dd/yy HH:mm zzz", 
                                  "M/d/yy HH:mm zzz", "MM/d/yy HH:mm zzz",                                 
                                  "M/dd/yyyy H:mm zzz", "MM/dd/yyyy H:mm zzz", 
                                  "M/d/yyyy H:mm zzz", "MM/d/yyyy H:mm zzz", 
                                  "M/dd/yy H:mm zzz", "MM/dd/yy H:mm zzz", 
                                  "M/d/yy H:mm zzz", "MM/d/yy H:mm zzz"};   
 IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat;
 DateTimeOffset result;

 do {
    conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),");
    conOut.Write("Then press Enter: ");
    input = conIn.ReadLine();
    conOut.WriteLine(); 
    if (DateTimeOffset.TryParseExact(input, formats, provider, 
                                    DateTimeStyles.AllowWhiteSpaces, 
                                    out result))
    {                                          
       break;
    }
    else
    {  
       Console.WriteLine("Unable to parse {0}.", input);      
       tries++;
    }
 } while (tries < 3);
 if (tries >= 3)
    Console.WriteLine("Exiting application without parsing {0}", input);
 else
    Console.WriteLine("{0} was converted to {1}", input, result.ToString());                                                     
 // Some successful sample interactions with the user might appear as follows:
 //    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 //    Then press Enter: 12/08/2007 6:54 -6:00
 //    
 //    12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00         
 //    
 //    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 //    Then press Enter: 12/8/2007 06:54 -06:00
 //    
 //    12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00
 //    
 //    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 //    Then press Enter: 12/5/07 6:54 -6:00
 //    
 //    12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 
 Dim conIn As TextReader = Console.In
 Dim conOut As TextWriter = Console.Out
 Dim tries As Integer = 0
 Dim input As String = String.Empty
 Dim formats() As String = {"M/dd/yyyy HH:m zzz", "MM/dd/yyyy HH:m zzz", _
                            "M/d/yyyy HH:m zzz", "MM/d/yyyy HH:m zzz", _
                            "M/dd/yy HH:m zzz", "MM/dd/yy HH:m zzz", _
                            "M/d/yy HH:m zzz", "MM/d/yy HH:m zzz", _                                 
                            "M/dd/yyyy H:m zzz", "MM/dd/yyyy H:m zzz", _
                            "M/d/yyyy H:m zzz", "MM/d/yyyy H:m zzz", _
                            "M/dd/yy H:m zzz", "MM/dd/yy H:m zzz", _
                            "M/d/yy H:m zzz", "MM/d/yy H:m zzz", _                               
                            "M/dd/yyyy HH:mm zzz", "MM/dd/yyyy HH:mm zzz", _
                            "M/d/yyyy HH:mm zzz", "MM/d/yyyy HH:mm zzz", _
                            "M/dd/yy HH:mm zzz", "MM/dd/yy HH:mm zzz", _
                            "M/d/yy HH:mm zzz", "MM/d/yy HH:mm zzz", _                                 
                            "M/dd/yyyy H:mm zzz", "MM/dd/yyyy H:mm zzz", _
                            "M/d/yyyy H:mm zzz", "MM/d/yyyy H:mm zzz", _
                            "M/dd/yy H:mm zzz", "MM/dd/yy H:mm zzz", _
                            "M/d/yy H:mm zzz", "MM/d/yy H:mm zzz"}   
 Dim provider As IFormatProvider = CultureInfo.InvariantCulture.DateTimeFormat
 Dim result As DateTimeOffset

 Do 
    conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),")
    conOut.Write("Then press Enter: ")
    input = conIn.ReadLine()
    conOut.WriteLine() 
    If DateTimeOffset.TryParseExact(input, formats, provider, _
                                    DateTimeStyles.AllowWhiteSpaces, _
                                    result) Then
       Exit Do
    Else
       Console.WriteLine("Unable to parse {0}.", input)      
       tries += 1
    End If
 Loop While tries < 3
 If tries >= 3 Then
    Console.WriteLine("Exiting application without parsing {0}", input)
 Else
    Console.WriteLine("{0} was converted to {1}", input, result.ToString())                                                     
 End If 
 ' Some successful sample interactions with the user might appear as follows:
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/08/2007 6:54 -6:00
 '    
 '    12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00         
 '    
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/8/2007 06:54 -06:00
 '    
 '    12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00
 '    
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/5/07 6:54 -6:00
 '    
 '    12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 

備註

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTimeOffset) 方法會剖析符合指派給 formats 陣列之任何一種模式之日期的字串表示。The TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTimeOffset) method parses the string representation of a date that matches any one of the patterns assigned to the formats array. 如果 input 字串與任何一種模式都不符合 styles 參數所定義的任何變化,則剖析作業會失敗,且方法會傳回 falseIf the input string does not match any one of these patterns with any variations defined by the styles parameter, the parsing operation fails and the method returns false. 除了比較 input 與包含格式規範的多個字串之外,此多載的行為與 DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 方法完全相同。Aside from comparing input to multiple strings that contain format specifiers, this overload behaves identically to the DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) method.

formats 參數是一個字串陣列,其專案包含單一標準格式規範,或一個或多個自訂格式規範,可定義 input的可能模式。The formats parameter is a string array whose elements contain either a single standard format specifier or one or more custom format specifiers that define the possible pattern of input. 如需有效格式化程式碼的詳細資訊,請參閱標準日期和時間格式字串自訂日期和時間格式字串For details about valid formatting codes, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如果 formats 中的相符元素包含 zzzzzz 自訂格式規範,以指出位移必須存在於 input中,則該位移必須包含負號或正號。If the matched element in formats includes the z, zz, or zzz custom format specifiers to indicate that an offset must be present in input, that offset must include either a negative sign or a positive sign. 如果缺少正負號,則剖析作業會失敗,且方法會傳回 falseIf the sign is missing, the parse operation fails and the method returns false.

重要

使用此多載的 formats 參數來指定多種格式,可協助減少許多使用者在輸入日期和時間時所經歷的挫折。Using the formats parameter of this overload to specify multiple formats can help reduce the frustration many users experience when they enter dates and times. 特別是,定義多個輸入模式的功能可以讓應用程式處理日期和時程表示法,其中可能包含或缺少前置零(以月、日、小時、分鐘和秒為單位)。In particular, the ability to define multiple input patterns enables an application to handle date and time representations that can either include or lack leading zeros in months, days, hours, minutes, and seconds. 此範例會提供這項說明。The example provides an illustration of this.

如果 formats 中符合的元素需要 input 包含日期,但不是時間,則會指派所產生的 DateTimeOffset 物件午夜(0:00:00)。If the matched element in formats requires that input contain a date but not a time, the resulting DateTimeOffset object is assigned a time of midnight (0:00:00). 如果 formats 中的相符元素要求輸入包含時間,而不是日期,則產生的 DateTimeOffset 物件會被指派本機系統上的目前日期。If the matched element in formats requires that input contain a time but not a date, the resulting DateTimeOffset object is assigned the current date on the local system. 如果 formats 中的相符元素不需要 input 包含位移,則產生之 DateTimeOffset 物件的位移會取決於 styles 參數的值。If the matched element in formats does not require that input contain an offset, the offset of the resulting DateTimeOffset object depends on the value of the styles parameter. 如果 styles 包含 AssumeLocal,當地時區的位移就會指派給 DateTimeOffset 物件。If styles includes AssumeLocal, the offset of the local time zone is assigned to the DateTimeOffset object. 如果 styles 包含 AssumeUniversal,則會將國際標準時間(UTC)位移(或 + 00:00)指派給 DateTimeOffset 物件。If styles includes AssumeUniversal, the Coordinated Universal Time (UTC) offset, or +00:00, is assigned to the DateTimeOffset object. 如果未指定任何值,則會使用本地時區的位移。If neither value is specified, the offset of the local time zone is used.

input 中使用的特定日期和時間符號和字串是由 formatProvider 參數所定義。The particular date and time symbols and strings used in input are defined by the formatProvider parameter. 如果 formats 的相符元素是標準格式規範字符串,則 input 的精確模式也是如此。The same is true for the precise pattern of input if the matching element of formats is a standard format specifier string. formatProvider 參數可以是下列其中一項:The formatProvider parameter can be either of the following:

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

styles 參數會定義是否允許在輸入字串中使用空白字元,表示如何剖析不含明確位移元件的字串,並支援以 UTC 轉換做為剖析作業的一部分。The styles parameter defines whether white space is permitted in the input string, indicates how strings without an explicit offset component are parsed, and supports UTC conversion as part of the parsing operation. 除了 NoCurrentDateDefault以外,支援 DateTimeStyles 列舉的所有成員。All members of the DateTimeStyles enumeration are supported except NoCurrentDateDefault. 下表列出每個支援成員的效果。The following table lists the effect of each supported member.

DateTimeStyles 成員DateTimeStyles member 行為Behavior
AdjustToUniversal 剖析 input,並在必要時將它轉換為 UTC。Parses input and, if necessary, converts it to UTC. 它相當於剖析字串,然後呼叫所傳回 DateTimeOffset 物件的 DateTimeOffset.ToUniversalTime 方法。It is equivalent to parsing a string, and then calling the DateTimeOffset.ToUniversalTime method of the returned DateTimeOffset object.
AssumeLocal 如果 formats 中的相符專案不需要 input 包含 offset 值,則傳回的 DateTimeOffset 物件會獲得當地時區的位移。If the matched element in formats does not require that input contain an offset value, the returned DateTimeOffset object is given the offset of the local time zone. 這是預設值。This is the default value.
AssumeUniversal 如果 formats 中的相符專案不需要 input 包含 offset 值,則會提供 UTC 位移(+ 00:00)給傳回的 DateTimeOffset 物件。If the matched element in formats does not require that input contain an offset value, the returned DateTimeOffset object is given the UTC offset (+00:00).
AllowInnerWhite 允許 input 包含不是由 formats中的元素所指定的內部泛空白字元。Allows input to include inner white space not specified by the elements in formats. 在日期和時間元件和個別元件(位移除外)之間可能會出現額外的空白字元,而在剖析字串時則會忽略這些空格。Extra white space can appear between date and time components and within individual components (except for the offset) and is ignored when parsing the string.
AllowLeadingWhite 允許 input 包含 formats中的元素未指定的開頭空白。Allows input to include leading spaces not specified by the elements in formats. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowTrailingWhite 允許 input 包含 formats中的元素未指定的尾端空格。Allows input to include trailing spaces not specified by the elements in formats. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowWhiteSpaces 允許 input 包含不是由 formats中的元素所指定的前置、尾端和內部空格。Allows input to include leading, trailing, and inner spaces not specified by the elements in formats. 剖析字串時,會忽略 formats 中符合的專案未指定的所有額外空白字元。All extra white-space characters not specified in the matched element in formats are ignored when parsing the string.
None 表示 input中不允許額外的空白字元。Indicates that additional white space is not permitted in input. 空白字元必須與 formats 中的特定元素所指定的完全相符,才會發生成功比對。White space must appear exactly as specified in a particular element in formats for a successful match to occur. 這是預設行為。This is the default behavior.
RoundtripKind 沒有任何作用,因為 DateTimeOffset 結構不包含 Kind 屬性。Has no effect because the DateTimeOffset structure does not include a Kind property.

給呼叫者的注意事項

.NET Framework 4.NET Framework 4中,如果要剖析的字串包含小時元件以及不在協定中的 AM/PM 指示項,則 TryParseExact 會傳回 falseIn the .NET Framework 4.NET Framework 4, the TryParseExact 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(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTimeOffset)

使用指定的格式、文化特性特定格式資訊與樣式,將字元範圍內的日期和時間表示,轉換為其相等的 DateTimeOffsetConverts the representation of a date and time in a character span to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. 日期和時間表示的格式必須完全符合指定的格式。The format of the date and time representation must match the specified format exactly.

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

參數

input
ReadOnlySpan<Char>

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

format
ReadOnlySpan<Char>

格式規範,其定義 input 所需的格式。A format specifier that defines the required format of input.

formatProvider
IFormatProvider

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

styles
DateTimeStyles

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

result
DateTimeOffset

如果轉換成功,方法傳回時內含的 DateTimeOffset 就會和 input 的日期和時間相等;如果轉換失敗,則為 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue if the conversion failed. 若...,轉換會失敗。The conversion fails if the

傳回

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

例外狀況

styles 包含未定義的 DateTimeStyles 值。styles includes an undefined DateTimeStyles value.
-或- 不支援 NoCurrentDateDefault-or- NoCurrentDateDefault is not supported.
-或- styles 包括互斥的 DateTimeStyles 值。-or- styles includes mutually exclusive DateTimeStyles values.

備註

這個多載就像 DateTimeOffset.ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) 方法,不同的是,如果轉換失敗,這個方法不會擲回例外狀況。This overload is like the DateTimeOffset.ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) method, except that this method does not throw an exception if the conversion fails. 它會剖析必須完全符合 format 參數所指定之模式的日期和時程表示。It parses the representation of a date and time that must exactly match the pattern specified by the format parameter. 如果 input 不符合此模式,且 styles 參數所定義的空白字元中有一些可能的變化,則剖析作業會失敗,且方法會傳回 falseIf input does not match this pattern, with some possible variations in white space defined by the styles parameter, the parsing operation fails and the method returns false.

format 參數是一個字元範圍,其中包含單一標準格式規範,或一或多個定義 input所需模式的自訂格式指定名稱。The format parameter is a character span that contains either a single standard format specifier or one or more custom format specifiers that define the required pattern of input. 如需有效格式化程式碼的詳細資訊,請參閱標準日期和時間格式字串自訂日期和時間格式字串For details about valid formatting codes, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如果 format 包括 zzzzzz 自訂格式規範,以指出位移必須存在於 input中,則該位移必須包含負號或正號。If format includes the z, zz, or zzz custom format specifiers to indicate that an offset must be present in input, that offset must include either a negative sign or a positive sign. 如果遺漏正負號,則剖析作業會失敗,且方法會傳回 falseIf the sign is missing, the parsing operation fails and the method returns false.

如果 format 需要 input 包含日期但不是時間,則會指派所產生的 DateTimeOffset 物件午夜(0:00:00)。If format requires that input contain a date but not a time, the resulting DateTimeOffset object is assigned a time of midnight (0:00:00). 如果 format 需要 input 包含時間,而不是日期,則產生的 DateTimeOffset 物件會被指派本機系統上的目前日期。If format requires that input contain a time but not a date, the resulting DateTimeOffset object is assigned the current date on the local system. 如果 format 不需要 input 包含位移,則產生之 DateTimeOffset 物件的位移取決於 styles 參數的值。If format does not require that input contain an offset, the offset of the resulting DateTimeOffset object depends on the value of the styles parameter. 如果 styles 包含 AssumeLocal,當地時區的位移就會指派給 DateTimeOffset 物件。If styles includes AssumeLocal, the offset of the local time zone is assigned to the DateTimeOffset object. 如果 styles 包含 AssumeUniversal,則會將國際標準時間(UTC)位移(或 + 00:00)指派給 DateTimeOffset 物件。If styles includes AssumeUniversal, the Coordinated Universal Time (UTC) offset, or +00:00, is assigned to the DateTimeOffset object. 如果未指定任何值,則會使用本地時區的位移。If neither value is specified, the offset of the local time zone is used.

input 中使用的特定日期和時間符號和字串是由 formatProvider 參數所定義。The particular date and time symbols and strings used in input are defined by the formatProvider parameter. 如果 format 是標準格式規範字符串,則 input 的精確模式也是如此。The same is true for the precise pattern of input if format is a standard format specifier string. formatProvider 參數可以是下列其中一項:The formatProvider parameter can be either of the following:

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

styles 參數會定義是否允許在輸入字串中使用空白字元,表示如何剖析不含明確位移元件的字串,並支援以 UTC 轉換做為剖析作業的一部分。The styles parameter defines whether white space is allowed in the input string, indicates how strings without an explicit offset component are parsed, and supports UTC conversion as part of the parsing operation. 除了 NoCurrentDateDefault以外,支援 DateTimeStyles 列舉的所有成員。All members of the DateTimeStyles enumeration are supported except NoCurrentDateDefault. 下表列出每個支援成員的效果。The following table lists the effect of each supported member.

DateTimeStyles 成員DateTimeStyles member 行為Behavior
AdjustToUniversal 剖析 input,並在必要時將它轉換為 UTC。Parses input and, if necessary, converts it to UTC. 它相當於剖析日期和時程表示法,然後呼叫所傳回 DateTimeOffset 物件的 DateTimeOffset.ToUniversalTime 方法。It is equivalent to parsing a date and time representation, and then calling the DateTimeOffset.ToUniversalTime method of the returned DateTimeOffset object.
AssumeLocal 如果 format 不需要 input 包含 offset 值,則會將本機時區的位移提供給傳回的 DateTimeOffset 物件。If format does not require that input contain an offset value, the returned DateTimeOffset object is given the offset of the local time zone. 這是預設行為。This is the default behavior.
AssumeUniversal 如果 format 不需要 input 包含 offset 值,則會提供 UTC 位移(+ 00:00)給傳回的 DateTimeOffset 物件。If format does not require that input contain an offset value, the returned DateTimeOffset object is given the UTC offset (+00:00).
AllowInnerWhite 允許 input 包含格式未指定的內部空白字元。Allows input to include inner white space not specified by format. 在日期和時間元件之間,以及在個別元件中,除了位移以外,額外的空白字元也可能會出現,而在剖析字串時則會予以忽略。Extra white space can appear between date and time components and within individual components, other than the offset, and is ignored when parsing the string.
AllowLeadingWhite 允許 input 包含 format未指定的前置空格。Allows input to include leading spaces not specified by format. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowTrailingWhite 允許 input 包含 format未指定的尾端空格。Allows input to include trailing spaces not specified by format. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowWhiteSpaces 允許 input 包含 format未指定的前置、尾端和內部空格。Allows input to include leading, trailing, and inner spaces not specified by format. 剖析字串時,會忽略 format 中未指定的所有額外空白字元。All extra white-space characters not specified in format are ignored when parsing the string.
None 表示 input中不允許額外的空白字元。Indicates that additional white space is not permitted in input. 空白字元必須完全如 format中所指定的樣子出現。White space must appear exactly as specified in format. 這是預設行為。This is the default behavior.
RoundtripKind 沒有任何作用,因為 DateTimeOffset 結構不包含 Kind 屬性。Has no effect, because the DateTimeOffset structure does not include a Kind property.

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

使用指定的格式、特定的文化特性格式資訊及樣式,將字元範圍中的日期和時間表示轉換為其對等的 DateTimeOffsetConverts the representation of a date and time in a character span to its DateTimeOffset equivalent using the specified formats, culture-specific format information, and style. 日期和時間表示的格式必須完全符合其中一個指定的格式。The format of the date and time representation must match one of the specified formats exactly.

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

參數

input
ReadOnlySpan<Char>

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

formats
String[]

標準或自訂格式字串的陣列,這些格式字串定義可接受的 input 格式。A array of standard or custom format strings that define the acceptable formats of input.

formatProvider
IFormatProvider

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

styles
DateTimeStyles

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

result
DateTimeOffset

如果轉換成功,方法傳回時內含的 DateTimeOffset 就會和 input 的日期和時間相等;如果轉換失敗,則為 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue if the conversion failed. 若...,轉換會失敗。The conversion fails if the

傳回

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

例外狀況

styles 包含未定義的 DateTimeStyles 值。styles includes an undefined DateTimeStyles value.
-或- 不支援 NoCurrentDateDefault-or- NoCurrentDateDefault is not supported.
-或- styles 包括互斥的 DateTimeStyles 值。-or- styles includes mutually exclusive DateTimeStyles values.

備註

這個方法會剖析符合指派給 formats 陣列之任何一種模式之日期的字串表示。This method parses the string representation of a date that matches any one of the patterns assigned to the formats array. 如果 input 不符合任何一種模式與 styles 參數所定義的任何變化,則剖析作業會失敗,且方法會傳回 falseIf input does not match any one of these patterns with any variations defined by the styles parameter, the parsing operation fails and the method returns false. 除了比較 input 與包含格式規範的多個字串之外,此多載的行為與 DateTimeOffset.ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) 方法完全相同。Aside from comparing input to multiple strings that contain format specifiers, this overload behaves identically to the DateTimeOffset.ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) method.

formats 參數是一個字串陣列,其專案包含單一標準格式規範,或一個或多個自訂格式規範,可定義 input的可能模式。The formats parameter is a string array whose elements contain either a single standard format specifier or one or more custom format specifiers that define the possible pattern of input. 如需有效格式化程式碼的詳細資訊,請參閱標準日期和時間格式字串自訂日期和時間格式字串For details about valid formatting codes, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如果 formats 中的相符元素包含 zzzzzz 自訂格式規範,以指出位移必須存在於 input中,則該位移必須包含負號或正號。If the matched element in formats includes the z, zz, or zzz custom format specifiers to indicate that an offset must be present in input, that offset must include either a negative sign or a positive sign. 如果缺少正負號,則剖析作業會失敗,且方法會傳回 falseIf the sign is missing, the parse operation fails and the method returns false.

重要

使用此多載的 formats 參數來指定多種格式,可協助減少許多使用者在輸入日期和時間時所經歷的挫折。Using the formats parameter of this overload to specify multiple formats can help reduce the frustration many users experience when they enter dates and times. 特別是,定義多個輸入模式的功能可以讓應用程式處理日期和時程表示法,其中可能包含或缺少前置零(以月、日、小時、分鐘和秒為單位)。In particular, the ability to define multiple input patterns enables an application to handle date and time representations that can either include or lack leading zeros in months, days, hours, minutes, and seconds. 此範例會提供這項說明。The example provides an illustration of this.

如果 formats 中符合的元素需要 input 包含日期,但不是時間,則會指派所產生的 DateTimeOffset 物件午夜(0:00:00)。If the matched element in formats requires that input contain a date but not a time, the resulting DateTimeOffset object is assigned a time of midnight (0:00:00). 如果 formats 中的相符元素要求輸入包含時間,而不是日期,則產生的 DateTimeOffset 物件會被指派本機系統上的目前日期。If the matched element in formats requires that input contain a time but not a date, the resulting DateTimeOffset object is assigned the current date on the local system. 如果 formats 中的相符元素不需要 input 包含位移,則產生之 DateTimeOffset 物件的位移會取決於 styles 參數的值。If the matched element in formats does not require that input contain an offset, the offset of the resulting DateTimeOffset object depends on the value of the styles parameter. 如果 styles 包含 DateTimeStyles.AssumeLocal,當地時區的位移就會指派給 DateTimeOffset 物件。If styles includes DateTimeStyles.AssumeLocal, the offset of the local time zone is assigned to the DateTimeOffset object. 如果 styles 包含 DateTimeStyles.AssumeUniversal,則會將國際標準時間(UTC)位移(或 + 00:00)指派給 DateTimeOffset 物件。If styles includes DateTimeStyles.AssumeUniversal, the Coordinated Universal Time (UTC) offset, or +00:00, is assigned to the DateTimeOffset object. 如果未指定任何值,則會使用本地時區的位移。If neither value is specified, the offset of the local time zone is used.

input 中使用的特定日期和時間符號是由 formatProvider 參數所定義。The particular date and time symbols used in input are defined by the formatProvider parameter. 如果 formats 的相符元素是標準格式規範字符串,則 input 的精確模式也是如此。The same is true for the precise pattern of input if the matching element of formats is a standard format specifier string. formatProvider 參數可以是下列其中一項:The formatProvider parameter can be either of the following:

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

styles 參數會定義是否允許在輸入字串中使用空白字元,表示如何剖析不含明確位移元件的字串,並支援以 UTC 轉換做為剖析作業的一部分。The styles parameter defines whether white space is permitted in the input string, indicates how strings without an explicit offset component are parsed, and supports UTC conversion as part of the parsing operation. 除了 NoCurrentDateDefault以外,支援 DateTimeStyles 列舉的所有成員。All members of the DateTimeStyles enumeration are supported except NoCurrentDateDefault. 下表列出每個支援成員的效果。The following table lists the effect of each supported member.

DateTimeStyles 成員DateTimeStyles member 行為Behavior
AdjustToUniversal 剖析 input,並在必要時將它轉換為 UTC。Parses input and, if necessary, converts it to UTC. 它相當於剖析字串,然後呼叫所傳回 DateTimeOffset 物件的 DateTimeOffset.ToUniversalTime 方法。It is equivalent to parsing a string, and then calling the DateTimeOffset.ToUniversalTime method of the returned DateTimeOffset object.
AssumeLocal 如果 formats 中的相符專案不需要 input 包含 offset 值,則傳回的 DateTimeOffset 物件會獲得當地時區的位移。If the matched element in formats does not require that input contain an offset value, the returned DateTimeOffset object is given the offset of the local time zone. 這是預設值。This is the default value.
AssumeUniversal 如果 formats 中的相符專案不需要 input 包含 offset 值,則會提供 UTC 位移(+ 00:00)給傳回的 DateTimeOffset 物件。If the matched element in formats does not require that input contain an offset value, the returned DateTimeOffset object is given the UTC offset (+00:00).
AllowInnerWhite 允許 input 包含不是由 formats中的元素所指定的內部泛空白字元。Allows input to include inner white space not specified by the elements in formats. 在日期和時間元件和個別元件(位移除外)之間可能會出現額外的空白字元,而在剖析字串時則會忽略這些空格。Extra white space can appear between date and time components and within individual components (except for the offset) and is ignored when parsing the string.
AllowLeadingWhite 允許 input 包含 formats中的元素未指定的開頭空白。Allows input to include leading spaces not specified by the elements in formats. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowTrailingWhite 允許 input 包含 formats中的元素未指定的尾端空格。Allows input to include trailing spaces not specified by the elements in formats. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowWhiteSpaces 允許 input 包含不是由 formats中的元素所指定的前置、尾端和內部空格。Allows input to include leading, trailing, and inner spaces not specified by the elements in formats. 剖析字串時,會忽略 formats 中符合的專案未指定的所有額外空白字元。All extra white-space characters not specified in the matched element in formats are ignored when parsing the string.
None 表示 input中不允許額外的空白字元。Indicates that additional white space is not permitted in input. 空白字元必須與 formats 中的特定元素所指定的完全相符,才會發生成功比對。White space must appear exactly as specified in a particular element in formats for a successful match to occur. 這是預設行為。This is the default behavior.
RoundtripKind 沒有任何作用,因為 DateTimeOffset 結構不包含 Kind 屬性。Has no effect because the DateTimeOffset structure does not include a Kind property.

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffsetConverts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly.

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

參數

input
String

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

format
String

格式規範,其定義 input 所需的格式。A format specifier that defines the required format of input.

formatProvider
IFormatProvider

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

styles
DateTimeStyles

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

result
DateTimeOffset

如果轉換成功,方法傳回時內含的 DateTimeOffset 就會和 input 的日期和時間相等;如果轉換失敗,則為 MinValueWhen the method returns, contains the DateTimeOffset equivalent to the date and time of input, if the conversion succeeded, or MinValue, if the conversion failed. 如果 input 參數為 null,或包含的日期和時間不是採用 formatprovider 所定義預期格式的有效字串表示。The conversion fails if the input parameter is null, or does not contain a valid string representation of a date and time in the expected format defined by format and provider. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

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

例外狀況

styles 包含未定義的 DateTimeStyles 值。styles includes an undefined DateTimeStyles value.

-或--or- 不支援 NoCurrentDateDefaultNoCurrentDateDefault is not supported.

-或--or- styles 包含互斥的 DateTimeStyles 值。styles includes mutually exclusive DateTimeStyles values.

範例

下列範例會使用 TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset) 方法搭配標準和自訂格式規範、不因文化特性而異,以及各種 DateTimeStyles 值來剖析數個日期和時間字串。The following example uses the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset) method with standard and custom format specifiers, the invariant culture, and various DateTimeStyles values to parse several date and time strings.

string dateString, format;  
DateTimeOffset result;
IFormatProvider provider = CultureInfo.InvariantCulture;

// Parse date-only value with invariant culture and assume time is UTC.
dateString = "06/15/2008";
format = "d";
if (DateTimeOffset.TryParseExact(dateString, format, provider, 
                                 DateTimeStyles.AssumeUniversal, 
                                 out result))
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
else
   Console.WriteLine("'{0}' is not in the correct format.", dateString);

// Parse date-only value with leading white space.
// Should return False because only trailing white space is  
// specified in method call.
dateString = " 06/15/2008";
if (DateTimeOffset.TryParseExact(dateString, format, provider, 
                                 DateTimeStyles.AllowTrailingWhite, 
                                 out result))
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
else
   Console.WriteLine("'{0}' is not in the correct format.", dateString);

// Parse date and time value, and allow all white space.
dateString = " 06/15/   2008  15:15    -05:00";
format = "MM/dd/yyyy H:mm zzz";
if (DateTimeOffset.TryParseExact(dateString, format, provider, 
                                 DateTimeStyles.AllowWhiteSpaces, 
                                 out result))
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
else
   Console.WriteLine("'{0}' is not in the correct format.", dateString);

// Parse date and time and convert to UTC.
dateString = "  06/15/2008 15:15:30 -05:00";   
format = "MM/dd/yyyy H:mm:ss zzz";       
if (DateTimeOffset.TryParseExact(dateString, format, provider, 
                                DateTimeStyles.AllowWhiteSpaces | 
                                DateTimeStyles.AdjustToUniversal, 
                                out result))
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
else
   Console.WriteLine("'{0}' is not in the correct format.", dateString);
// The example displays the following output:
//    '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00.
//    ' 06/15/2008' is not in the correct format.
//    ' 06/15/   2008  15:15    -05:00' converts to 6/15/2008 3:15:00 PM -05:00.
//    '  06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00.
Dim dateString, format As String  
Dim result As DateTimeOffset
Dim provider As CultureInfo = CultureInfo.InvariantCulture

' Parse date-only value with invariant culture and assume time is UTC.
dateString = "06/15/2008"
format = "d"
If DateTimeOffset.TryParseExact(dateString, format, provider, _
                                   DateTimeStyles.AssumeUniversal, _
                                   result) Then
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Else
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End If 

' Parse date-only value with leading white space.
' Should return False because only trailing white space is  
' specified in method call.
dateString = " 06/15/2008"
If DateTimeOffset.TryParseExact(dateString, format, provider, _
                                DateTimeStyles.AllowTrailingWhite, _
                                result) Then
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Else
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End If 

' Parse date and time value, and allow all white space.
dateString = " 06/15/   2008  15:15    -05:00"
format = "MM/dd/yyyy H:mm zzz"
If DateTimeOffset.TryParseExact(dateString, format, provider, _
                                DateTimeStyles.AllowWhiteSpaces, _
                                result) Then
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Else
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End If 

' Parse date and time and convert to UTC.
dateString = "  06/15/2008 15:15:30 -05:00"   
format = "MM/dd/yyyy H:mm:ss zzz"       
If DateTimeOffset.TryParseExact(dateString, format, provider, _
                                DateTimeStyles.AllowWhiteSpaces Or _
                                DateTimeStyles.AdjustToUniversal, _
                                result) Then
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Else
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End If 
' The example displays the following output:
'    '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00.
'    ' 06/15/2008' is not in the correct format.
'    ' 06/15/   2008  15:15    -05:00' converts to 6/15/2008 3:15:00 PM -05:00.
'    '  06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00.

下列範例會使用各種不同的 DateTimeStyles 值來剖析預期符合ISO 8601的字串陣列。The following example uses a variety of DateTimeStyles values to parse an array of strings that are expected to conform to ISO 8601. 如範例的輸出所示,格式正確的字串會在下列情況下無法剖析:As the output from the example shows, strings that are in the proper format fail to parse if:

除非在方法呼叫中提供了 DateTimeStyles.AssumeUniversal 旗標,否則未指定 UTC 時差的字串會假設為具有當地時區的位移(在此案例中為-07:00,這會反映太平洋日光節約時區的位移)。Strings that do not specify a UTC offset are assumed to have the offset of the local time zone (in this case, -07:00, which reflects the offset of the Pacific Daylight Time zone) unless the DateTimeStyles.AssumeUniversal flag is supplied in the method call. 在這種情況下,它們會被假設為全球協調時間。In that case, they are assumed to be Universal Coordinated Time.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = { "2018-08-18T12:45:16.0000000Z",
                               "2018/08/18T12:45:16.0000000Z",
                               "2018-18-08T12:45:16.0000000Z",
                               "2018-08-18T12:45:16.0000000",                               
                               " 2018-08-18T12:45:16.0000000Z ",
                               "2018-08-18T12:45:16.0000000+02:00",
                               "2018-08-18T12:45:16.0000000-07:00" }; 
      
      ParseWithISO8601(dateStrings, DateTimeStyles.None);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal);   }

   private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles)
   {   
      Console.WriteLine($"Parsing with {styles}:");
      DateTimeOffset date;
      foreach (var dateString in dateStrings)
      {
         if (DateTimeOffset.TryParseExact(dateString, "O", null, styles, out date))
         {
            Console.WriteLine($"   {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}");
         }
         else
         {
            Console.WriteLine($"   Unable to convert '{dateString}'");
         }   
      } 
   }
}
// The example displays the following output:
//      Parsing with None:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         Unable to convert '2018/08/18T12:45:16.0000000Z'
//         Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AllowWhiteSpaces:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         Unable to convert '2018/08/18T12:45:16.0000000Z'
//         Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//          2018-08-18T12:45:16.0000000Z       --> 2018-08-18 12:45:16 +00:00
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AdjustToUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         Unable to convert '2018/08/18T12:45:16.0000000Z'
//         Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
//         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 10:45:16 +00:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 19:45:16 +00:00
//
//      -----
//
//      Parsing with AssumeLocal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         Unable to convert '2018/08/18T12:45:16.0000000Z'
//         Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AssumeUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         Unable to convert '2018/08/18T12:45:16.0000000Z'
//         Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
//         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim dateStrings() = { "2018-08-18T12:45:16.0000000Z",
                            "2018/08/18T12:45:16.0000000Z",
                            "2018-18-08T12:45:16.0000000Z",
                            "2018-08-18T12:45:16.0000000",                               
                            " 2018-08-18T12:45:16.0000000Z ",
                            "2018-08-18T12:45:16.0000000+02:00",
                            "2018-08-18T12:45:16.0000000-07:00" } 
      
      ParseWithISO8601(dateStrings, DateTimeStyles.None)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal)   
   End Sub

   Private Sub ParseWithISO8601(dateStrings() As String, styles As DateTimeStyles)
      Console.WriteLine($"Parsing with {styles}:")
      Dim dat As DateTimeOffset
      For Each dateStr In dateStrings
         If DateTimeOffset.TryParseExact(dateStr, "O", Nothing, styles, dat) Then
            Console.WriteLine($"   {dateStr,-35} --> {dat:yyyy-MM-dd HH:mm:ss.FF zzz}")
         Else
            Console.WriteLine($"   Unable to convert '{dateStr}'")
         End If   
      Next 
   End Sub
End Module
' The example displays the following output:
'      Parsing with None:
'         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'         Unable to convert '2018/08/18T12:45:16.0000000Z'
'         Unable to convert '2018-18-08T12:45:16.0000000Z'
'         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
'         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
'         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
'         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
'
'      -----
'
'      Parsing with AllowWhiteSpaces:
'         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'         Unable to convert '2018/08/18T12:45:16.0000000Z'
'         Unable to convert '2018-18-08T12:45:16.0000000Z'
'         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
'          2018-08-18T12:45:16.0000000Z       --> 2018-08-18 12:45:16 +00:00
'         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
'         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
'
'      -----
'
'      Parsing with AdjustToUniversal:
'         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'         Unable to convert '2018/08/18T12:45:16.0000000Z'
'         Unable to convert '2018-18-08T12:45:16.0000000Z'
'         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
'         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
'         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 10:45:16 +00:00
'         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 19:45:16 +00:00
'
'      -----
'
'      Parsing with AssumeLocal:
'         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'         Unable to convert '2018/08/18T12:45:16.0000000Z'
'         Unable to convert '2018-18-08T12:45:16.0000000Z'
'         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
'         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
'         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
'         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
'
'      -----
'
'      Parsing with AssumeUniversal:
'         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'         Unable to convert '2018/08/18T12:45:16.0000000Z'
'         Unable to convert '2018-18-08T12:45:16.0000000Z'
'         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
'         Unable to convert ' 2018-08-18T12:45:16.0000000Z '
'         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
'         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00

備註

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset) 方法的這個多載就像 DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 方法,不同的是,這個方法不會在轉換失敗時擲回例外狀況。This overload of the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset) method is like the DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) method, except that this method does not throw an exception if the conversion fails. 它會剖析必須完全符合 format 參數所指定之模式的日期和時間的字串表示。It parses the string representation of a date and time that must exactly match the pattern specified by the format parameter. 如果 input 字串與此模式不相符,而且 styles 參數所定義的空白字元中有一些可能的變化,則剖析作業會失敗,且方法會傳回 falseIf the input string does not match this pattern, with some possible variations in white space defined by the styles parameter, the parsing operation fails and the method returns false.

format 參數是一個字串,其中包含單一標準格式規範,或一或多個定義 input所需模式的自訂格式指定名稱。The format parameter is a string that contains either a single standard format specifier or one or more custom format specifiers that define the required pattern of input. 如需有效格式化程式碼的詳細資訊,請參閱標準日期和時間格式字串自訂日期和時間格式字串For details about valid formatting codes, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如果 format 包括 zzzzzz 自訂格式規範,以指出位移必須存在於 input中,則該位移必須包含負號或正號。If format includes the z, zz, or zzz custom format specifiers to indicate that an offset must be present in input, that offset must include either a negative sign or a positive sign. 如果遺漏正負號,則剖析作業會失敗,且方法會傳回 falseIf the sign is missing, the parsing operation fails and the method returns false.

如果 format 需要 input 包含日期但不是時間,則會指派所產生的 DateTimeOffset 物件午夜(0:00:00)。If format requires that input contain a date but not a time, the resulting DateTimeOffset object is assigned a time of midnight (0:00:00). 如果 format 需要 input 包含時間,而不是日期,則產生的 DateTimeOffset 物件會被指派本機系統上的目前日期。If format requires that input contain a time but not a date, the resulting DateTimeOffset object is assigned the current date on the local system. 如果 format 不需要 input 包含位移,則產生之 DateTimeOffset 物件的位移取決於 styles 參數的值。If format does not require that input contain an offset, the offset of the resulting DateTimeOffset object depends on the value of the styles parameter. 如果 styles 包含 AssumeLocal,當地時區的位移就會指派給 DateTimeOffset 物件。If styles includes AssumeLocal, the offset of the local time zone is assigned to the DateTimeOffset object. 如果 styles 包含 AssumeUniversal,則會將國際標準時間(UTC)位移(或 + 00:00)指派給 DateTimeOffset 物件。If styles includes AssumeUniversal, the Coordinated Universal Time (UTC) offset, or +00:00, is assigned to the DateTimeOffset object. 如果未指定任何值,則會使用本地時區的位移。If neither value is specified, the offset of the local time zone is used.

input 中使用的特定日期和時間符號和字串是由 formatProvider 參數所定義。The particular date and time symbols and strings used in input are defined by the formatProvider parameter. 如果 format 是標準格式規範字符串,則 input 的精確模式也是如此。The same is true for the precise pattern of input if format is a standard format specifier string. formatProvider 參數可以是下列其中一項:The formatProvider parameter can be either of the following:

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

styles 參數會定義是否允許在輸入字串中使用空白字元,表示如何剖析不含明確位移元件的字串,並支援以 UTC 轉換做為剖析作業的一部分。The styles parameter defines whether white space is allowed in the input string, indicates how strings without an explicit offset component are parsed, and supports UTC conversion as part of the parsing operation. 除了 NoCurrentDateDefault以外,支援 DateTimeStyles 列舉的所有成員。All members of the DateTimeStyles enumeration are supported except NoCurrentDateDefault. 下表列出每個支援成員的效果。The following table lists the effect of each supported member.

DateTimeStyles 成員DateTimeStyles member 行為Behavior
AdjustToUniversal 剖析 input,並在必要時將它轉換為 UTC。Parses input and, if necessary, converts it to UTC. 它相當於剖析字串,然後呼叫所傳回 DateTimeOffset 物件的 DateTimeOffset.ToUniversalTime 方法。It is equivalent to parsing a string, and then calling the DateTimeOffset.ToUniversalTime method of the returned DateTimeOffset object.
AssumeLocal 如果 format 不需要 input 包含 offset 值,則會將本機時區的位移提供給傳回的 DateTimeOffset 物件。If format does not require that input contain an offset value, the returned DateTimeOffset object is given the offset of the local time zone. 這是預設行為。This is the default behavior.
AssumeUniversal 如果 format 不需要 input 包含 offset 值,則會提供 UTC 位移(+ 00:00)給傳回的 DateTimeOffset 物件。If format does not require that input contain an offset value, the returned DateTimeOffset object is given the UTC offset (+00:00).
AllowInnerWhite 允許 input 包含格式未指定的內部空白字元。Allows input to include inner white space not specified by format. 在日期和時間元件之間,以及在個別元件中,除了位移以外,額外的空白字元也可能會出現,而在剖析字串時則會予以忽略。Extra white space can appear between date and time components and within individual components, other than the offset, and is ignored when parsing the string.
AllowLeadingWhite 允許 input 包含 format未指定的前置空格。Allows input to include leading spaces not specified by format. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowTrailingWhite 允許 input 包含 format未指定的尾端空格。Allows input to include trailing spaces not specified by format. 剖析字串時,會忽略這些。These are ignored when parsing the string.
AllowWhiteSpaces 允許 input 包含 format未指定的前置、尾端和內部空格。Allows input to include leading, trailing, and inner spaces not specified by format. 剖析字串時,會忽略 format 中未指定的所有額外空白字元。All extra white-space characters not specified in format are ignored when parsing the string.
None 表示 input中不允許額外的空白字元。Indicates that additional white space is not permitted in input. 空白字元必須完全如 format中所指定的樣子出現。White space must appear exactly as specified in format. 這是預設行為。This is the default behavior.
RoundtripKind 沒有任何作用,因為 DateTimeOffset 結構不包含 Kind 屬性。Has no effect, because the DateTimeOffset structure does not include a Kind property.

給呼叫者的注意事項

.NET Framework 4.NET Framework 4中,如果要剖析的字串包含小時元件以及不在協定中的 AM/PM 指示項,則 TryParseExact 會傳回 falseIn the .NET Framework 4.NET Framework 4, the TryParseExact 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.

另請參閱

適用於