DateTimeOffset.ParseExact 方法

定義

將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合指定的格式。

多載

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

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合其中一個指定的格式。

ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合指定的格式。

ParseExact(String, String, IFormatProvider)

使用指定的格式以及特定文化特性的格式資訊,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合指定的格式。

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

使用指定的格式、文化特性特定格式資訊與樣式,將代表日期和時間的字元,轉換為其相等的 DateTimeOffset。 日期和時間表示的格式必須完全符合指定的格式。

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

使用指定的格式、文化特性特定格式資訊與樣式,將包含日期和時間字串表示的字元範圍,轉換為其相等的 DateTimeOffset。 日期和時間表示的格式必須完全符合其中一個指定的格式。

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

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合其中一個指定的格式。

public:
 static DateTimeOffset ParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string[] formats, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles);
static member ParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As String, formats As String(), formatProvider As IFormatProvider, styles As DateTimeStyles) As DateTimeOffset

參數

input
String

字串,包含要轉換的日期和時間。

formats
String[]

格式規範陣列,定義 input 的預期格式。

formatProvider
IFormatProvider

物件,其提供關於 input 的特定文化特性格式資訊。

styles
DateTimeStyles

列舉值的位元組合,其表示 input 所允許的格式。

傳回

DateTimeOffset

物件,與 input 參數中包含的日期和時間相等,如 formatsformatProviderstyles 參數所指定。

例外狀況

位移大於 14 小時或小於 -14 小時。

-或-

styles 包含不支援的值。

-或-

styles 參數包含無法搭配使用的 DateTimeStyles 值。

inputnull

input 為空字串 ("")。

-或-

input 不包含日期與時間的有效字串表示。

-或-

formats 的項目未包含有效的格式規範。

-或-

小時元件和 input 中的 AM/PM 指示項不相符。

範例

下列範例會針對日期和時間和位移值的字串表示定義多個輸入格式,然後將使用者輸入的字串傳遞至 DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 方法。

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 = new 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();
   try
   {
      result = DateTimeOffset.ParseExact(input, formats, provider,
                                         DateTimeStyles.AllowWhiteSpaces);
      break;
   }
   catch (FormatException)
   {
      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
let input = String.Empty
let formats = 
    [| @"@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" |]
let provider = CultureInfo.InvariantCulture.DateTimeFormat

let mutable result = None
let mutable tries = 0
while tries < 3 && result.IsNone do
    printfn "Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"
    printf "Then press Enter: "
    let input = stdin.ReadLine()
    printfn ""
    try
        result <- 
            DateTimeOffset.ParseExact(input, formats, provider, DateTimeStyles.AllowWhiteSpaces) 
            |> Some
    with :? FormatException ->
        printfn $"Unable to parse {input}."
        tries <- tries + 1

match result with
| Some result ->
    printfn $"{input} was converted to {result}"
| None ->
    printfn $"Exiting application without parsing {input}"

// 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() 
    Try
       result = DateTimeOffset.ParseExact(input, formats, provider, _
                                          DateTimeStyles.AllowWhiteSpaces)
       Exit Do
    Catch e As FormatException
       Console.WriteLine("Unable to parse {0}.", input)      
       tries += 1
    End Try
 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

備註

方法 DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 會剖析日期的字串表示,該日期符合指派給 formats 參數的任何一個模式。 input如果字串與參數所 styles 定義的任何變化不符上述任何一個模式,則 方法會 FormatException 擲回 。 除了與多個格式模式比較 input 之外,這個多載的行為與 方法相同 DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles)

參數 formats 是字串陣列,其元素包含單一標準格式規範或定義參數可能模式的 input 一或多個自訂格式規範。 呼叫 方法時, input 必須符合下列其中一個模式。 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串。 如果 中的 formats 相符專案包含 zzzzzz 自訂格式規範,表示位移必須存在於 中 input ,該位移必須包含負號或正負號。 如果遺漏符號,方法會 FormatException 擲回 。

重要

formats使用這個多載的 參數來指定多個格式,有助於減少使用者在輸入日期和時間時遇到的挫折。 特別是,定義多個輸入模式的能力可讓應用程式處理日期和時程表示法,這些標記法可以包含或缺少月份、天數、小時、分鐘和秒的前置零。 此範例提供此範例的圖例。

如果 中的 formats 相符專案需要 input 包含日期而非時間,則產生的 DateTimeOffset 物件會指派午夜 (0:00:00) 的時間。 如果 中的 formats 相符專案需要 input 包含時間,但不包含日期,則產生的 DateTimeOffset 物件會指派本機系統上的目前日期。 如果 中的 formats 相符專案不需要 input 包含位移,則結果 DateTimeOffset 物件的位移取決於 參數的值 styles 。 如果 styles 包含 AssumeLocal ,則會將當地時區的位移指派給 DateTimeOffset 物件。 如果 styles 包含 AssumeUniversal ,則會將國際標準時間 (UTC) 位移或 +00:00 指派給 DateTimeOffset 物件。 如果未指定任何值,則會使用當地時區的位移。

input 所使用的特定日期和時間符號和字串是由 formatProvider 參數所定義。 如果 的 input 相符專案 formats 是標準格式規範字符串,則的精確格式也是如此。 參數 formatProvider 可以是下列其中一項:

如果 為 formatprovider null ,則會 CultureInfo 使用對應至目前文化特性的物件。

參數 styles 會定義輸入字串中是否允許空白字元、指出剖析不含明確位移元件的字串的方式,並支援在剖析作業期間進行 UTC 轉換。 除了 之外 NoCurrentDateDefault ,支援列舉的所有成員 DateTimeStyles 。 下表列出每個支援成員的效果。

DateTimeStyles 成員 行為
AdjustToUniversal 視需要剖析 input ,並將它轉換成 UTC。 它相當於剖析字串,然後呼叫 DateTimeOffset.ToUniversalTimeDateTimeOffset 回物件的 方法。
AssumeLocal 如果 中的 formats 相符專案不需要 input 包含位移值,傳 DateTimeOffset 回的物件就會獲得當地時區的位移。 這是預設值。
AssumeUniversal 如果 中的 formats 相符專案不需要 input 包含位移值,傳 DateTimeOffset 回的物件就會獲得 UTC 位移 (+00:00) 。
AllowInnerWhite 允許 input 包含 未指定的內部空白字元 format 。 除了位移 () 以外,日期與時間元件之間和個別元件之間可能會顯示額外的空白字元,而且會在剖析字串時忽略。
AllowLeadingWhite 允許 input 包含 未指定的 formats 前置空格。 剖析字串時會忽略這些值。
AllowTrailingWhite 允許 input 包含 未指定的 formats 尾端空格。 剖析字串時會忽略這些值。
AllowWhiteSpaces 允許 input 包含開頭、尾端和未指定的 formats 內部空格。 剖析字串時,會忽略 中 formats 相符專案未指定的所有額外空白字元。
None 表示 中不允許額外的空白字元 input 。 空白字元必須與 的特定元素 formats 中所指定完全相同,才能發生相符專案。 此為預設行為。
RoundtripKind 沒有作用, DateTimeOffset 因為 結構不包含 Kind 屬性。

給呼叫者的注意事項

在 .NET Framework 4 中 ParseExact ,如果要剖析的字串包含小時元件和未合約的 AM/PM 指示項,則方法會擲 FormatException 回 。 在 .NET Framework 3.5 和更早版本中,會忽略 AM/PM 指示項。

另請參閱

適用於

ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合指定的格式。

public:
 static DateTimeOffset ParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles);
static member ParseExact : string * string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As String, format As String, formatProvider As IFormatProvider, styles As DateTimeStyles) As DateTimeOffset

參數

input
String

字串,包含要轉換的日期和時間。

format
String

格式規範,其定義 input 應有的格式。

formatProvider
IFormatProvider

物件,其提供關於 input 的特定文化特性格式資訊。

styles
DateTimeStyles

列舉值的位元組合,其表示 input 所允許的格式。

傳回

DateTimeOffset

物件,與 input 參數中包含的日期和時間相等,如 formatformatProviderstyles 參數所指定。

例外狀況

位移大於 14 小時或小於 -14 小時。

-或-

styles 參數包含不支援的值。

-或-

styles 參數包含無法搭配使用的 DateTimeStyles 值。

inputnull

-或-

formatnull

input 為空字串 ("")。

-或-

input 不包含日期與時間的有效字串表示。

-或-

format 為空字串。

-或-

小時元件和 input 中的 AM/PM 指示項不相符。

範例

下列範例會 DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 使用 方法搭配標準和自訂格式規範、不變異文化特性,以及各種 DateTimeStyles 值來剖析數個日期和時間字串。

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

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

// Parse date-only value with leading white space.
// Should throw a FormatException because only trailing white space is
// specified in method call.
dateString = " 06/15/2008";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowTrailingWhite);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   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";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowWhiteSpaces);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   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";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowWhiteSpaces |
                                      DateTimeStyles.AdjustToUniversal);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   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.
let provider = CultureInfo.InvariantCulture

// Parse date-only value with invariant culture and assume time is UTC.
let dateString = "06/15/2008"
let format = "d"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AssumeUniversal)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date-only value with leading white space.
// Should throw a FormatException because only trailing white space is
// specified in method call.
let dateString = " 06/15/2008"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AllowTrailingWhite)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date and time value, and allow all white space.
let dateString = " 06/15/   2008  15:15    -05:00"
let format = "MM/dd/yyyy H:mm zzz"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AllowWhiteSpaces)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date and time and convert to UTC.
let dateString = "  06/15/2008 15:15:30 -05:00"
let format = "MM/dd/yyyy H:mm:ss zzz"
try
    let result = 
        DateTimeOffset.ParseExact(dateString, format, provider,
                                  DateTimeStyles.AllowWhiteSpaces |||
                                  DateTimeStyles.AdjustToUniversal)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// 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"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AssumeUniversal)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' Parse date-only value with leading white space.
' Should throw a FormatException because only trailing white space is  
' specified in method call.
dateString = " 06/15/2008"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowTrailingWhite)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' 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"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowWhiteSpaces)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' 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"       
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowWhiteSpaces Or _
                                      DateTimeStyles.AdjustToUniversal)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 
' 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的字串陣列。 如範例的輸出所示,如果下列情況,格式正確的字串將無法剖析:

除非方法呼叫中提供旗標,否則未指定 UTC 位移的字串會假設具有當地時區的位移 (,否則 DateTimeStyles.AssumeUniversal 為 -07:00) 。 在此情況下,它們會假設為通用國際標準時間。

module parseexact_iso8601_2

open System
open System.Globalization

let 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" |] 

let parseWithISO8601 dateStrings styles =
    printfn $"Parsing with {styles}:"
    for dateString in dateStrings do
        try
            let date = DateTimeOffset.ParseExact(dateString, "O", null, styles)
            printfn $"""   {dateString,-35} --> {date.ToString "yyyy-MM-dd HH:mm:ss.FF zzz"}"""
        with :? FormatException ->
            printfn $"   FormatException: Unable to convert '{dateString}'"

parseWithISO8601 dateStrings DateTimeStyles.None
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AllowWhiteSpaces
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AdjustToUniversal
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AssumeLocal
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AssumeUniversal


// The example displays the following output:
//      Parsing with None:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
//         FormatException: 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
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}:");
      foreach (var dateString in dateStrings)
      {
         try {
            var date = DateTimeOffset.ParseExact(dateString, "O", null, styles);
            Console.WriteLine($"   {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}");
         }
         catch (FormatException)
         {
            Console.WriteLine($"   FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: 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
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
//         FormatException: 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}:")
      For Each dateStr In dateStrings
         Try 
            Dim dat = DateTimeOffset.ParseExact(dateString, "O", Nothing, styles)
            Console.WriteLine($"   {dateString,-35} --> {dat:yyyy-MM-dd HH:mm:ss.FF zzz}")
         catch e As FormatException
            Console.WriteLine($"   FormatException: Unable to convert '{dateString}'")
         End Try   
      Next 
   End Sub
End Module
' The example displays the following output:
'      Parsing with None:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AllowWhiteSpaces:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AdjustToUniversal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AssumeLocal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AssumeUniversal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'

備註

方法 DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 會剖析日期的字串表示,其格式必須是 參數所 format 定義的格式。 它也需要 <Date> 日期和時間字串表示的 、 <Time> 和 <Offset> 元素,以 所 format 指定的順序顯示。 input如果字串不符合 參數的 format 模式,且參數所 styles 定義的任何變化,方法會 FormatException 擲回 。 相反地,方法會 DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) 剖析格式提供者物件所辨識之任一格式中日期的 DateTimeFormatInfo 字串表示。 Parse 也允許 <Date> 日期和時間字串表示的 、 <Time> 和 <Offset> 元素以任何順序顯示。

參數 format 是包含單一標準格式規範的字串,或是一或多個自訂格式規範,可定義參數的必要模式 input 。 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串。 如果 format 包含 zzzzzz 自訂格式規範,表示位移必須存在於 中 input ,該位移必須包含負號或正負號。 如果遺漏符號,方法會 FormatException 擲回 。

如果需要 format 包含 input 日期,但不包含時間,則產生的 DateTimeOffset 物件會指派午夜 (0:00:00) 的時間。 如果需要 format 包含 input 時間,但不包含日期,則產生的 DateTimeOffset 物件會指派本機系統上的目前日期。 如果 format 不需要包含 input 位移,則產生的 DateTimeOffset 物件位移取決於 參數的值 styles 。 如果 styles 包含 AssumeLocal ,則會將當地時區的位移指派給 DateTimeOffset 物件。 如果 styles 包含 AssumeUniversal ,則會將國際標準時間 (UTC) 位移或 +00:00 指派給 DateTimeOffset 物件。 如果未指定任何值,則會使用當地時區的位移。

input 所使用的特定日期和時間符號和字串是由 formatProvider 參數所定義。 如果 format 是標準格式規範字符串,則這同樣適用于 的 input 精確格式。 參數 formatProvider 可以是下列其中一項:

如果 為 formatprovider null ,則會 CultureInfo 使用對應至目前文化特性的物件。

參數 styles 會定義輸入字串中是否允許空白字元、指出如何剖析不含明確位移元件的字串,並支援 UTC 轉換作為剖析作業的一部分。 除了 之外 NoCurrentDateDefault ,支援列舉的所有成員 DateTimeStyles 。 下表列出每個支援成員的效果。

DateTimeStyles 成員 行為
AdjustToUniversal 視需要剖析 input ,並將它轉換成 UTC。 它相當於剖析字串,然後呼叫 DateTimeOffset.ToUniversalTimeDateTimeOffset 回物件的 方法。
AssumeLocal 如果 format 不需要包含 input 位移值,則傳 DateTimeOffset 回的物件會獲得當地時區的位移。 這是預設值。
AssumeUniversal 如果 format 不需要包含 input 位移值,傳 DateTimeOffset 回的物件就會獲得 UTC 位移 (+00:00) 。
AllowInnerWhite 允許 input 包含 未指定的內部空白字元 format 。 在日期和時間元件和個別元件之間可以顯示額外的空白字元,並在剖析字串時予以忽略。
AllowLeadingWhite 允許 input 包含 未指定的 format 前置空格。 剖析字串時會忽略這些值。
AllowTrailingWhite 允許 input 包含 未指定的 format 尾端空格。 剖析字串時會忽略這些值。
AllowWhiteSpaces 允許 input 包含開頭、尾端和未指定的 format 內部空格。 剖析字串時,會忽略 中 format 未指定的所有額外空白字元。
None 表示 中不允許額外的空白字元 input 。 空白字元必須與 中指定的 format 完全相同。 此為預設行為。
RoundtripKind 沒有作用, DateTimeOffset 因為 結構不包含 Kind 屬性。

給呼叫者的注意事項

在 .NET Framework 4 中 ParseExact ,如果要剖析的字串包含小時元件和未合約的 AM/PM 指示項,則方法會擲 FormatException 回 。 在 .NET Framework 3.5 和更早版本中,會忽略 AM/PM 指示項。

另請參閱

適用於

ParseExact(String, String, IFormatProvider)

使用指定的格式以及特定文化特性的格式資訊,將日期和時間的指定字串表示,轉換為其相等的 DateTimeOffset。 字串表示的格式必須完全符合指定的格式。

public:
 static DateTimeOffset ParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider? formatProvider);
static member ParseExact : string * string * IFormatProvider -> DateTimeOffset
Public Shared Function ParseExact (input As String, format As String, formatProvider As IFormatProvider) As DateTimeOffset

參數

input
String

字串,包含要轉換的日期和時間。

format
String

格式規範,其定義 input 應有的格式。

formatProvider
IFormatProvider

物件,其提供關於 input 的特定文化特性格式資訊。

傳回

DateTimeOffset

物件,與 input 中包含的日期和時間相等,如 formatformatProvider 所指定。

例外狀況

位移大於 14 小時或小於 -14 小時。

inputnull

-或-

formatnull

input 為空字串 ("")。

-或-

input 不包含日期與時間的有效字串表示。

-或-

format 為空字串。

-或-

小時元件和 input 中的 AM/PM 指示項不相符。

範例

下列範例會 DateTimeOffset.ParseExact(String, String, IFormatProvider) 使用 方法搭配標準和自訂格式規範,以及不可變的文化特性來剖析數個日期和時間字串。

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

// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date and time with offset without offset//s minutes.
// Should throw a FormatException because "zzz" specifier requires leading
// zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   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 -07:00.
//    6/15/2008 is not in the correct format.
//    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
//    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
let provider = CultureInfo.InvariantCulture

// Parse date-only value with invariant culture.
let dateString = "06/15/2008"
let format = "d"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
let dateString = "6/15/2008"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date and time with custom specifier.
let dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
let format = "ddd dd MMM yyyy h:mm tt zzz"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date and time with offset without offset//s minutes.
// Should throw a FormatException because "zzz" specifier requires leading
// zero in hours.
let dateString = "Sun 15 Jun 2008 8:30 AM -06"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// The example displays the following output:
//    06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00.
//    6/15/2008 is not in the correct format.
//    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
//    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
Dim dateString, format As String  
Dim result As DateTimeOffset
Dim provider As CultureInfo = CultureInfo.InvariantCulture

' Parse date-only value with invariant culture.
dateString = "06/15/2008"
format = "d"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date-only value without leading zero in month using "d" format.
' Should throw a FormatException because standard short date pattern of 
' invariant culture requires two-digit month.
dateString = "6/15/2008"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
format = "ddd dd MMM yyyy h:mm tt zzz"        
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date and time with offset without offset's minutes.
' Should throw a FormatException because "zzz" specifier requires leading  
' zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 
' The example displays the following output:
'    06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00.
'    6/15/2008 is not in the correct format.
'    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
'    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.

下列範例會剖析預期符合 ISO 8601的字串陣列。 如範例的輸出所示,具有前置或尾端空格的字串無法成功剖析,如同具有超出範圍的日期和時間元素字串一樣。

module parseexact_iso8601

open System

let dateStrings =
    [ "2018-08-18T12:45:16.0000000Z"
      "2018/08/18T12:45:16.0000000Z"
      "2018-18-08T12:45:16.0000000Z"
      " 2018-08-18T12:45:16.0000000Z "
      "2018-08-18T12:45:16.0000000+02:00"
      "2018-08-18T12:45:16.0000000-07:00" ]

for dateString in dateStrings do
    try
        let date =
            DateTimeOffset.ParseExact(dateString, "O", null)

        printfn $"""{dateString, -35} --> {date.ToString "yyyy-MM-dd HH:mm:ss.FF zzz"}"""
    with :? FormatException -> printfn $"FormatException: Unable to convert '{dateString}'"


// The example displays the following output:
//      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//      FormatException: 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
using System;

public class Example2
{
   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.0000000Z ",
                               "2018-08-18T12:45:16.0000000+02:00",
                               "2018-08-18T12:45:16.0000000-07:00" }; 
      
      foreach (var dateString in dateStrings)
      {
         try {
            var date = DateTimeOffset.ParseExact(dateString, "O", null);
            Console.WriteLine($"{dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}");
         }
         catch (FormatException)
         {
            Console.WriteLine($"FormatException: Unable to convert '{dateString}'");
         }   
      } 
   }
}
// The example displays the following output:
//      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//      FormatException: 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
Public Module Example
   Public Sub Main()
      Dim dateStrings() As String = { "2018-08-18T12:45:16.0000000Z",
                                      "2018/08/18T12:45:16.0000000Z",
                                      "2018-18-08T12:45:16.0000000Z",
                                      " 2018-08-18T12:45:16.0000000Z ",
                                      "2018-08-18T12:45:16.0000000+02:00",
                                      "2018-08-18T12:45:16.0000000-07:00" } 
      
      For Each dateStr In dateStrings
         Try 
            Dim dat = DateTimeOffset.ParseExact(dateStr, "O", Nothing)
            Console.WriteLine($"{dateStr,-35} --> {dat:yyyy-MM-dd HH:mm:ss.FF zzz}")
         Catch  e As FormatException
            Console.WriteLine($"FormatException: Unable to convert '{dateStr}'")
         End Try   
      Next 
   End Sub
End Module
' The example displays the following output:
'      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
'      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
'      FormatException: 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

備註

方法 ParseExact(String, String, IFormatProvider) 會剖析日期的字串標記法,其格式必須是 參數所 format 定義的格式。 它也需要 <Date> 日期和時間之字串表示的 、 <Time> 和 <Offset> 元素以 所 format 指定的順序顯示。 input如果字串不符合此參數 format ,則方法會擲回 FormatException 。 相反地,方法會 DateTimeOffset.Parse(String, IFormatProvider) 剖析格式提供者 DateTimeFormatInfo 物件所辨識之任一格式的日期字串表示。 Parse 也允許 <Date> 日期和時間字串表示的 、 <Time> 和 <Offset> 元素以任何順序顯示。

參數 format 是包含單一標準格式規範或一或多個自訂格式規範的字串,可定義參數的必要格式 input 。 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串。 如果 format 包含 zzzzzz 自訂格式規範,表示位移必須存在於 input 中,該位移必須包含負號或正負號。 如果遺漏符號,方法會擲回 FormatException

如果需要 format 包含 input 日期而非時間,則產生的 DateTimeOffset 物件會指派午夜 (0:00:00) 的時間。 如果需要 format 包含 input 時間,但不包含日期,產生的 DateTimeOffset 物件會指派本機系統上的目前日期。 如果 format 不需要包含 input 位移,則產生的 DateTimeOffset 物件會指派本機系統的時區位移。

input 所使用的特定日期和時間符號和字串是由 formatProvider 參數所定義,就像是標準格式規範字符串的精確格式 input format 一樣。 參數 formatProvider 可以是下列其中一項:

如果 formatprovidernull ,則會 CultureInfo 使用對應至目前文化特性的物件。

給呼叫者的注意事項

在 .NET Framework 4 中,如果要剖析的字串包含小時元件,以及未在合約中的 AM/PM 指示項, ParseExact 則方法會 FormatException 擲回 。 在 .NET Framework 3.5 和舊版中,會忽略 AM/PM 指示項。

另請參閱

適用於

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

使用指定的格式、文化特性特定格式資訊與樣式,將代表日期和時間的字元,轉換為其相等的 DateTimeOffset。 日期和時間表示的格式必須完全符合指定的格式。

public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTimeOffset

參數

input
ReadOnlySpan<Char>

代表日期和時間的字元範圍。

format
ReadOnlySpan<Char>

包含定義 input 預期格式之格式規範的字元範圍。

formatProvider
IFormatProvider

提供關於 input 之特定文化特性格式資訊的物件。

styles
DateTimeStyles

列舉值的位元組合,其表示 input 所允許的格式。

傳回

DateTimeOffset

物件,與 input 參數中包含的日期和時間相等,如 formatformatProviderstyles 參數所指定。

例外狀況

位移大於 14 小時或小於 -14 小時。 -或- 參數 styles 包含不支援的值。 -或- 參數 styles 包含 DateTimeStyles 不能一起使用的值。

input 是空的字元範圍。 -或- input 不包含日期和時間的有效字串表示。 -或- format 是空的字元範圍。 -或- 中的 input 小時元件和 AM/PM 指示項不同意。

備註

這個方法會剖析代表日期的字元範圍,此範圍必須是 參數所 format 定義的格式。 它也需要 <Date> 日期和時間之字串表示的 、 <Time> 和 <Offset> 元素以 所 format 指定的順序顯示。 如果 input 不符合 format 模式,方法會擲回 FormatException 。 相反地,方法會 DateTimeOffset.Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) 剖析格式提供者 DateTimeFormatInfo 物件所辨識之任一格式的日期字串表示。 Parse 也允許 <Date> 日期和時間字串表示的 、 <Time> 和 <Offset> 元素以任何順序顯示。

參數 format 是字元範圍,其中包含單一字元標準格式規範或定義參數所需格式的 input 一或多個自訂格式規範。 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串。 如果 format 包含 zzzzzz 自訂格式規範,表示位移必須存在於 input 中,該位移必須包含負號或正負號。 如果遺漏符號,方法會擲回 FormatException

如果需要 format 包含 input 日期而非時間,則產生的 DateTimeOffset 物件會指派午夜 (0:00:00) 的時間。 如果需要 format 包含 input 時間,但不包含日期,產生的 DateTimeOffset 物件會指派本機系統上的目前日期。 如果 format 不需要包含 input 位移,則產生的 DateTimeOffset 物件會指派本機系統的時區位移。

input 所使用的特定日期和時間符號和字串是由 formatProvider 參數所定義,就像是標準格式規範時的精確格式 input format 一樣。 參數 formatProvider 可以是下列其中一項:

如果 formatprovidernull ,則會 CultureInfo 使用對應至目前文化特性的物件。

適用於

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

使用指定的格式、文化特性特定格式資訊與樣式,將包含日期和時間字串表示的字元範圍,轉換為其相等的 DateTimeOffset。 日期和時間表示的格式必須完全符合其中一個指定的格式。

public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), formats As String(), formatProvider As IFormatProvider, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTimeOffset

參數

input
ReadOnlySpan<Char>

包含要轉換之日期和時間的字元範圍。

formats
String[]

格式規範陣列,定義 input 的預期格式。

formatProvider
IFormatProvider

物件,其提供關於 input 的特定文化特性格式資訊。

styles
DateTimeStyles

列舉值的位元組合,其表示 input 所允許的格式。

傳回

DateTimeOffset

物件,與 input 參數中包含的日期和時間相等,如 formatsformatProviderstyles 參數所指定。

例外狀況

位移大於 14 小時或小於 -14 小時。 -或- styles 包括不支援的值。 -或- 參數 styles 包含 DateTimeStyles 無法一起使用的值。

input 是空的字元範圍。 -或- input 不包含日期和時間的有效字串表示。 -或- 的 元素 formats 不包含有效的格式規範。 -或- 中的 input 小時元件和 AM/PM 指示項不一致。

備註

這個方法會剖析字元範圍,代表符合指派給 formats 參數之任一模式的日期。 如果 input 不符合上述任何一個模式與 參數所 styles 定義的任何變化,則方法會擲回 FormatException 。 除了比較 input 多個格式設定模式之外,這個多載的行為與 方法相同 DateTimeOffset.ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

參數 formats 是字串陣列,其元素包含單一標準格式規範或一或多個自訂格式規範,以定義參數的 input 可能模式。 呼叫 方法時, input 必須符合下列其中一個模式。 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串。 如果 中的 formats 相符專案包含 zzzzzz 自訂格式規範,表示位移必須存在於 input 中,該位移必須包含負號或正負號。 如果遺漏符號,方法會擲回 FormatException

重要

formats使用此多載的 參數來指定多個格式,有助於減少許多使用者在輸入日期和時間時遇到的挫折。 特別是,定義多個輸入模式的能力可讓應用程式處理日期和時程表示法,這些標記法可以包含或缺少月份、天數、小時、分鐘和秒的前置零。

如果 中的 formats 相符專案需要 input 包含日期而非時間,則產生的 DateTimeOffset 物件會指派午夜 (0:00:00) 的時間。 如果 中的 formats 相符專案需要 input 包含時間,但不是日期,則產生的 DateTimeOffset 物件會指派本機系統上的目前日期。 如果 中的 formats 相符專案不需要包含 input 位移,則產生的 DateTimeOffset 物件位移取決於 參數的值 styles 。 如果 styles 包含 AssumeLocal ,則會將本機時區的位移指派給 DateTimeOffset 物件。 如果 styles 包含 AssumeUniversal ,則會將國際標準時間 (UTC) 位移或 +00:00 指派給 DateTimeOffset 物件。 如果未指定任何值,則會使用當地時區的位移。

input 所使用的特定日期和時間符號和字串是由 參數所 formatProvider 定義。 如果 的 formats 相符專案是標準格式 input 規範字符串,則相同的是 。 參數 formatProvider 可以是下列其中一項:

如果 formatprovidernull ,則會 CultureInfo 使用對應至目前文化特性的物件。

參數 styles 會定義輸入字串中是否允許空白字元、指出剖析沒有明確位移元件的字串如何剖析,並支援在剖析作業期間進行 UTC 轉換。 除了 之外 NoCurrentDateDefault ,支援列舉的所有成員 DateTimeStyles 。 下表列出每個支援成員的效果。

DateTimeStyles 成員 行為
AdjustToUniversal 視需要剖析 input ,並將它轉換成 UTC。 它相當於剖析字串,然後呼叫 DateTimeOffset.ToUniversalTimeDateTimeOffset 回物件的 方法。
AssumeLocal 如果 中的 formats 相符專案不需要 input 包含位移值,傳 DateTimeOffset 回的物件就會獲得當地時區的位移。 這是預設值。
AssumeUniversal 如果 中的 formats 相符專案不需要 input 包含位移值,傳 DateTimeOffset 回的物件就會獲得 UTC 位移 (+00:00) 。
AllowInnerWhite 允許 input 包含 未指定的內部空白字元 format 。 除了位移 () 以外,日期與時間元件之間和個別元件之間可能會顯示額外的空白字元,而且會在剖析字串時忽略。
AllowLeadingWhite 允許 input 包含 未指定的 formats 前置空格。 剖析字串時會忽略這些值。
AllowTrailingWhite 允許 input 包含 未指定的 formats 尾端空格。 剖析字串時會忽略這些值。
AllowWhiteSpaces 允許 input 包含開頭、尾端和未指定的 formats 內部空格。 剖析字串時,會忽略 中 formats 相符專案未指定的所有額外空白字元。
None 表示 中不允許額外的空白字元 input 。 空白字元必須與 的特定元素 formats 中所指定完全相同,才能發生相符專案。 此為預設行為。
RoundtripKind 沒有作用, DateTimeOffset 因為 結構不包含 Kind 屬性。

適用於