DateTime.Parse 方法

定義

將日期和時間的字串表示,轉換為其相等的 DateTime

多載

Parse(String)

使用目前文化特性的慣例,將日期和時間的字串表示轉換為其對 DateTime 等的 。

Parse(ReadOnlySpan<Char>, IFormatProvider)

將字元範圍剖析為值。

Parse(String, IFormatProvider)

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTime

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTime

Parse(String, IFormatProvider, DateTimeStyles)

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTime

範例

Numerous examples that call the DateTime.Parse method are interspersed throughout the Remarks section of this article and in the documentation for the individual DateTime.Parse overloads.

注意

此文章中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。 選取 [執行] 按鈕以在互動式視窗中執行範例。 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。

Try.NET 內嵌程式碼執行器與 Playground 的當地時區是全球標準時間 (UTC)。 這可能會影響示範 DateTimeDateTimeOffsetTimeZoneInfo 型別與其成員之範例的行為與輸出。

您也可以下載一組 DateTime.Parse 完整的範例,這些範例包含在 C# 的 .NET Core 專案中

備註

本節內容:

我呼叫哪一種方法?

收件者 呼叫
使用目前文化特性的慣例來剖析日期和時間字串。 Parse(String) 多載
使用特定文化特性的慣例來剖析日期和時間字串。 Parse(String, IFormatProvider) 多載 (請參閱剖析 和文化慣例)
剖析具有特殊樣式元素的日期和時間字串, (例如空白字元或沒有空白字元) 。 Parse(String, IFormatProvider, DateTimeStyles) 多載
剖析必須具有特定格式的日期和時間字串。 DateTime.ParseExactDateTime.TryParseExact
剖析日期和時間字串,並執行 UTC 或當地時間的轉換。 Parse(String, IFormatProvider, DateTimeStyles) 多載
剖析日期和時間字串,而不處理例外狀況。 DateTime.TryParse 方法
還原 () 格式化作業所建立的日期和時間值。 將 「o」 或 「r」 標準格式字串傳遞至 ToString(String) 方法,並使用 呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載 DateTimeStyles.RoundtripKind
跨電腦剖析固定格式的日期和時間字串, (和可能的文化特性) 界限。 DateTime.ParseExactDateTime.TryParseExact 方法

要剖析的字串

方法 Parse 會嘗試將日期和時間值的字串表示轉換成它的 DateTime 對等專案。 它會嘗試完全剖析輸入字串,而不會擲 FormatException 回例外狀況。

重要

如果剖析作業因為無法辨識的字串格式而失敗,則 Parse 方法會 FormatException 擲回 ,而 TryParse 方法會傳 false 回 。 因為例外狀況處理可能很昂貴,所以當剖析作業預期成功時,您應該使用 Parse ,因為輸入來源受信任。 TryParse 最好是剖析失敗的可能性,特別是因為輸入來源不受信任,或者您有合理的預設值來取代無法成功剖析的字串。

要剖析的字串可以採用下列任何形式:

  • 具有日期和時間元件的字串。

  • 具有日期但沒有時間元件的字串。 如果時間元件不存在,此方法會假設午夜 12:00。 如果日期元件有兩位數的年份,它會根據 Calendar.TwoDigitYearMax 目前文化特性的目前行事曆或指定的文化特性的目前行事曆 (,如果您使用多載與非 Null provider 引數) ,則會轉換成年份。

  • 包含日期元件的字串,只包含月份和年份,但沒有日期元件。 方法假設月份的第一天。

  • 字串,包含只包含月份和日期,但沒有年份元件。 方法假設目前年份。

  • 具有時間但沒有日期元件的字串。 方法會假設目前的日期,除非您呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載並包含在 DateTimeStyles.NoCurrentDateDefault 引數中 styles ,在此情況下,方法會假設 0001 年 1 月 1 日。

  • 包含僅包含小時和 AM/PM 指示項之時間元件的字串,不含日期元件。 方法假設目前的日期和時間沒有分鐘和秒數。 您可以藉由呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載並包含在 DateTimeStyles.NoCurrentDateDefault 引數中 styles 來變更此行為,在此情況下,方法會假設 0001 年 1 月 1 日的日期。

  • 包含時區資訊的字串,且符合 ISO 8601。 在下列範例中,第一個字串會指定國際標準時間 (UTC) ,而第二個字串會指定時區中的時間,其時間早于 UTC 7 小時:

    「2008-11-01T19:35:00.00000000Z」 「2008-11-01T19:35:00.0000000-07:00」

  • 包含 GMT 指示項且符合 RFC 1123 時間格式的字串;例如:

    「Sat, 01 Nov 2008 19:35:00 GMT」

  • 包含日期和時間以及時區位移資訊的字串;例如:

    "03/01/2009 05:42:00 -5:00"

下列範例會使用目前文化特性的格式慣例來剖析每個格式的字串,在此案例中為 en-US 文化特性:

using System;

public class Example
{
   public static void Main()
   {
      (string dateAsString, string description)[]  dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"),
                                                                ("08/18/2018", "String with a date component only"),
                                                                ("8/2018", "String with a month and year component only"),
                                                                ("8/18", "String with a month and day component only"),
                                                                ("07:22:16", "String with a time component only"),
                                                                ("7 PM", "String with an hour and AM/PM designator only"),
                                                                ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),
                                                                ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                                                                ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                                                                ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) };

      Console.WriteLine($"Today is {DateTime.Now:d}\n");

      foreach (var item in dateInfo) {
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}");
      }
   }
}
// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
module Parse6

open System

let  dateInfo = 
    [ "08/18/2018 07:22:16", "String with a date and time component"
      "08/18/2018", "String with a date component only"
      "8/2018", "String with a month and year component only"
      "8/18", "String with a month and day component only"
      "07:22:16", "String with a time component only"
      "7 PM", "String with an hour and AM/PM designator only"
      "2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"
      "2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"
      "Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"
      "08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ]

printfn $"Today is {DateTime.Now:d}\n"

for dateAsString, description in dateInfo do
    printfn $"""{description + ":",-52} '{dateAsString}' --> {DateTime.Parse(dateAsString)}"""


// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

Public Module Strings
   Public Sub Main()
      Dim dateInfo() As (dateAsString As String, description As String) = 
                     { ("08/18/2018 07:22:16", "String with a date and time component"),
                       ("08/18/2018", "String with a date component only"),
                       ("8/2018", "String with a month and year component only"),
                       ("8/18", "String with a month and day component only"),
                       ("07:22:16", "String with a time component only"),
                       ("7 PM", "String with an hour and AM/PM designator only"),
                       ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),   
                       ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                       ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                       ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }
   
      Console.WriteLine($"Today is {Date.Now:d}{vbCrLf}")
      
      For Each item in dateInfo
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}")        
      Next
   End Sub
End Module
' The example displays output like the following:
'   Today is 2/22/2018
'   
'   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
'   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
'   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
'   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
'   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
'   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
'   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
'   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
'   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
'   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

如果輸入字串代表剖析方法所使用的日曆中的閏日, (請參閱剖析 和文化慣例) ,則 Parse 方法會成功剖析字串。 如果輸入字串代表非閏年的閏日,此方法會 FormatException 擲回 。

Parse因為 方法會嘗試使用目前或指定文化特性的格式規則來剖析日期和時間的字串表示,所以嘗試剖析不同文化特性的字串可能會失敗。 若要剖析不同地區設定的特定日期和時間格式,請使用 方法的 DateTime.ParseExact 其中一個多載並提供格式規範。

剖析和文化慣例

除非要剖析的字串 (,否則方法的所有多載 Parse 都會區分文化特性,如下表所表示 s ,) 符合 ISO 8601 模式。 剖析作業會使用 衍生物件中的 DateTimeFormatInfo 格式資訊,如下所示:

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。 此變更對使用這些日曆的所有應用程式都有影響。 如需詳細資訊,以及判斷您的應用程式是否受到影響,請參閱在 .net 的日文日曆中處理新的紀元。 如需在 Windows 系統上測試您的應用程式以確保其在年代的就緒狀態變更的相關資訊,請參閱準備您的應用程式以進行日本時代變更。 針對支援多個紀元日曆的 .NET 功能,以及在使用支援多個紀元的行事歷時的最佳作法,請參閱 使用紀元

如果您呼叫 provider 格式化資訊衍生自
Parse(String) - 目前文化特性 (DateTimeFormatInfo.CurrentInfo 屬性)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) DateTimeFormatInfo 物件 指定的 DateTimeFormatInfo 物件
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) null 目前文化特性 (DateTimeFormatInfo.CurrentInfo 屬性)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) CultureInfo 物件 CultureInfo.DateTimeFormat 屬性
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) 自訂 IFormatProvider 實作 IFormatProvider.GetFormat 方法

當格式化資訊衍生自 DateTimeFormatInfo 物件時, DateTimeFormatInfo.Calendar 屬性會定義剖析作業中使用的行事曆。

如果您使用物件與標準文化特性不同的自訂設定來剖析日期和時間字串 DateTimeFormatInfo ,請使用 ParseExact 方法,而不是 Parse 方法,以改善成功轉換的機會。 非標準日期和時間字串可能很複雜且難以剖析。 方法 Parse 會嘗試剖析具有數個隱含剖析模式的字串,其中所有模式都可能會失敗。 相反地,方法 ParseExact 會要求您明確指定一或多個可能成功的確切剖析模式。 For more information, see the "DateTimeFormatInfo and Dynamic Data" section in the DateTimeFormatInfo topic.

重要

請注意,特定文化特性的格式化慣例是動態的,而且可能會變更。 這表示剖析作業取決於預設 (目前) 文化特性的格式設定慣例,或指定 IFormatProvider 代表非變異文化特性以外的文化特性的物件,如果發生下列任何一項,則可能會意外失敗:

  • 文化特性特定資料在.NET Framework的主要或次要版本之間變更,或因為更新至現有版本的.NET Framework而變更。
  • 特定文化特性資料會反映使用者喜好設定,其可能會因電腦而異,或與會話的會話不同。
  • 特定文化特性資料代表取代文化特性,此取代文化特性會覆寫標準文化特性或自訂文化特性的設定。

若要避免剖析與文化資料變更相關聯的資料和時間字串時發生困難,您可以使用不因文化特性而異的文化特性來剖析日期和時間字串,或者您可以呼叫 ParseExactTryParseExact 方法,並指定要剖析的字串確切格式。 如果您要序列化和還原序列化日期和時間資料,您可以使用不因文化特性而異的格式化慣例,或者可以使用二進位格式序列化和還原序列化 DateTime 值。

For more information see the "Dynamic culture data" section in the CultureInfo topic and the "Persisting DateTime values" section in the DateTime topic.

剖析和樣式專案

所有 Parse 多載都會忽略輸入字串中開頭、內部或尾端空白字元 (,如下表所表示 s) 。 日期和時間可以用一對開頭和尾端的 NUMBER SIGN 字元括住, (「#」、U+0023) ,並以一或多個 Null 字元結尾, (U+0000) 。

此外,多 Parse(String, IFormatProvider, DateTimeStyles) 載具有 styles 由一或多個列舉成員組成的參數 DateTimeStyles 。 此參數會定義應該如何 s 解譯,以及剖析作業應該如何轉換成 s 日期和時間。 下表描述每個 DateTimeStyles 成員對剖析作業的影響。

DateTimeStyles 成員 對轉換的影響
AdjustToUniversal 視需要剖析 s ,並將它轉換成 UTC,如下所示:

- 如果 s 包含時區位移,或如果 s 不包含時區資訊,但 styles 包含 AssumeLocal 旗標,方法會剖析字串、呼叫 ToUniversalTime 以將傳 DateTime 回的值轉換為 UTC,並將 屬性設定 KindDateTimeKind.Utc
- 如果 s 指出它代表 UTC,或如果 s 不包含時區資訊,但 styles 包含 AssumeUniversal 旗標,方法會剖析字串、在傳 DateTime 回的值上執行無時區轉換,並將 屬性設定 KindDateTimeKind.Utc
- 在其他所有情況下,旗標沒有任何作用。
AllowInnerWhite 這個值會被忽略。 在 的 s 日期和時間元素中,一律允許內部空白字元。
AllowLeadingWhite 這個值會被忽略。 在 的 s 日期和時間元素中,一律允許前置空白字元。
AllowTrailingWhite 這個值會被忽略。 在 的 s 日期和時間元素中,一律允許尾端空白字元。
AllowWhiteSpaces 指定可能包含 s 前置、內部和尾端空白字元。 這是預設行為。 無法藉由提供更嚴格的 DateTimeStyles 列舉值來覆寫它,例如 None
AssumeLocal 指定如果 s 缺少任何時區資訊,則會假設當地時間。 除非有 AdjustToUniversal 旗標, Kind 否則傳 DateTime 回值的 屬性會設定為 DateTimeKind.Local
AssumeUniversal 指定如果 s 缺少任何時區資訊,則會假設 UTC。 AdjustToUniversal除非有 旗標,否則 方法會將傳 DateTime 回的值從 UTC 轉換為當地時間,並將其 屬性設定 KindDateTimeKind.Local
None 雖然有效,但會忽略此值。
RoundtripKind 對於包含時區資訊的字串,嘗試防止日期和時間字串 DateTime 轉換成值,其 屬性設定 DateTimeKind.Local 為 的當地時間 Kind 。 一般而言,這類字串是藉由呼叫 DateTime.ToString(String) 方法,並使用 「o」、「r」 或 「u」 標準格式規範來建立。

傳回值和 DateTime.Kind

DateTime.Parse 載會傳 DateTime 回值,其 Kind 屬性包含時區資訊。 它可以指出時間是:

一般而言,方法會 ParseDateTime 回 屬性為 DateTimeKind.Unspecified 的 物件 Kind 。 不過, Parse 方法也可以執行時區轉換,並根據 和 styles 參數的值,以不同的方式設定 屬性的值 Kind s

如果 時區轉換 Kind 屬性
s 包含時區資訊。 日期和時間會轉換成當地時區中的時間。 DateTimeKind.Local
s 包含時區資訊,並 styles 包含 AdjustToUniversal 旗標。 日期和時間會轉換成國際標準時間 (UTC) 。 DateTimeKind.Utc
s 包含 Z 或 GMT 時區指示項,並 styles 包含 RoundtripKind 旗標。 日期和時間會解譯為 UTC。 DateTimeKind.Utc

下列範例會將包含時區資訊的日期字串轉換成當地時區中的時間:

using System;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = {"2008-05-01T07:34:42-5:00",
                              "2008-05-01 7:34:42Z",
                              "Thu, 01 May 2008 07:34:42 GMT"};
      foreach (string dateString in dateStrings)
      {
         DateTime convertedDate = DateTime.Parse(dateString);
         Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
      }
   }
}
// These calls to the DateTime.Parse method display the following output:
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
open System

let dateStrings = 
    [ "2008-05-01T07:34:42-5:00"
      "2008-05-01 7:34:42Z"
      "Thu, 01 May 2008 07:34:42 GMT" ]

for dateString in dateStrings do
    let convertedDate = DateTime.Parse dateString
    printfn $"Converted {dateString} to {convertedDate.Kind} time {convertedDate}"

// These calls to the DateTime.Parse method display the following output:
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Module Example
   Public Sub Main()
      Dim dateStrings() As String = {"2008-05-01T07:34:42-5:00", 
                                     "2008-05-01 7:34:42Z", 
                                     "Thu, 01 May 2008 07:34:42 GMT"}
      
      For Each dateStr In dateStrings
         Dim convertedDate As Date = Date.Parse(dateStr)
         Console.WriteLine($"Converted {dateStr} to {convertedDate.Kind} time {convertedDate}")
      Next 
   End Sub
End Module
' These calls to the DateTime.Parse method display the following output:
'   Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
'   Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
'   Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM

您也可以使用 DateTimeStyles.RoundtripKind 旗標,在格式化和剖析作業期間保留日期和時間 Kind 的 屬性值。 下列範例說明旗標如何使用 RoundtripKind 「o」、「r」 或 「u」 格式規範,對轉換成字串的值影響剖析作業 DateTime

   string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00",
                               "2008-09-15T09:30:41.7752486Z",
                               "2008-09-15T09:30:41.7752486",
                               "2008-09-15T09:30:41.7752486-04:00",
                               "Mon, 15 Sep 2008 09:30:41 GMT" };
   foreach (string formattedDate in formattedDates)
   {
      Console.WriteLine(formattedDate);
      DateTime roundtripDate = DateTime.Parse(formattedDate, null,
                                              DateTimeStyles.RoundtripKind);
      Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.");

      DateTime noRoundtripDate = DateTime.Parse(formattedDate, null,
                                                DateTimeStyles.None);
      Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.");
   }
// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
let formattedDates = 
    [ "2008-09-15T09:30:41.7752486-07:00"
      "2008-09-15T09:30:41.7752486Z"
      "2008-09-15T09:30:41.7752486"
      "2008-09-15T09:30:41.7752486-04:00"
      "Mon, 15 Sep 2008 09:30:41 GMT" ]

for formattedDate in formattedDates do
    printfn $"{formattedDate}"
    let roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind)
    printfn $"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time."

    let noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None)
    printfn $"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time."

// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
Dim formattedDates() = { "2008-09-15T09:30:41.7752486-07:00", 
                           "2008-09-15T09:30:41.7752486Z",  
                           "2008-09-15T09:30:41.7752486",  
                           "2008-09-15T09:30:41.7752486-04:00", 
                           "Mon, 15 Sep 2008 09:30:41 GMT" }
For Each formattedDate In formattedDates
   Console.WriteLine(formattedDate)
   Dim roundtripDate = DateTime.Parse(formattedDate, Nothing,  
                                      DateTimeStyles.RoundtripKind)                        
   Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.")                                          
   Dim noRoundtripDate = DateTime.Parse(formattedDate, Nothing,                                                                                                  DateTimeStyles.None)
   Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.")
Next         
' The example displays the following output:
'       2008-09-15T09:30:41.7752486-07:00
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486Z
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'       2008-09-15T09:30:41.7752486-04:00
'          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'       Mon, 15 Sep 2008 09:30:41 GMT
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.

Parse(String)

使用目前文化特性的慣例,將日期和時間的字串表示轉換為其對 DateTime 等的 。

public:
 static DateTime Parse(System::String ^ s);
public static DateTime Parse (string s);
static member Parse : string -> DateTime
Public Shared Function Parse (s As String) As DateTime

參數

s
String

字串,包含要轉換的日期和時間。 如需詳細資訊,請參閱要剖析的字串

傳回

DateTime

物件,與 s 中包含的日期和時間相等。

例外狀況

snull

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

範例

下列範例會剖析數個日期和時間值的字串表示方式:

  • 使用預設格式提供者,提供電腦目前用來產生範例輸出之文化特性的格式慣例。 此範例的輸出會反映 en-US 文化特性的格式設定慣例。

  • 使用預設樣式值,也就是 AllowWhiteSpaces

它會處理 FormatException 方法嘗試使用一些其他文化特性的格式化慣例來剖析日期和時間字串表示時擲回的例外狀況。 它也會示範如何成功剖析未使用目前文化特性格式設定慣例的日期和時間值。

using System;
using System.Globalization;

public class DateTimeParser
{
   public static void Main()
   {
      // Assume the current culture is en-US.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      // Use standard en-US date and time value
      DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Reverse month and day to conform to the fr-FR culture.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Call another overload of Parse to successfully convert string
      // formatted according to conventions of fr-FR culture.
      try {
         dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Parse string with date but no time component.
      dateString = "2/16/2008";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }
   }
}
// The example displays the following output to the console:
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
//       Unable to convert '16/02/2008 12:15:12'.
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Assume the current culture is en-US.
    // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

    // Use standard en-US date and time value
    let dateString = "2/16/2008 12:15:12 PM"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Reverse month and day to conform to the fr-FR culture.
    // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
    let dateString = "16/02/2008 12:15:12"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        Console.WriteLine("Unable to convert '{0}'.", dateString)

    // Call another overload of Parse to successfully convert string
    // formatted according to conventions of fr-FR culture.
    try
        let dateValue = DateTime.Parse(dateString, CultureInfo("fr-FR", false))
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Parse string with date but no time component.
    let dateString = "2/16/2008"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    0

// The example displays the following output to the console:
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
//       Unable to convert '16/02/2008 12:15:12'.
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Imports System.Globalization

Class DateTimeParser
   Public Shared Sub Main()
      ' Assume the current culture is en-US. 
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      ' Use standard en-US date and time value
      Dim dateValue As Date
      Dim dateString As String = "2/16/2008 12:15:12 PM"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
            
      ' Reverse month and day to conform to the fr-FR culture.
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' Call another overload of Parse to successfully convert string
      ' formatted according to conventions of fr-FR culture.      
      Try
         dateValue = Date.Parse(dateString, New CultureInfo("fr-FR", False))
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
      
      ' Parse string with date but no time component.
      dateString = "2/16/2008"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
   End Sub 
End Class 
' The example displays the following output to the console:
'       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
'       Unable to convert '16/02/2008 12:15:12'.
'       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
'       '2/16/2008' converted to 2/16/2008 12:00:00 AM.

備註

如果 s 包含時區資訊,這個方法會 DateTime 傳回其 Kind 屬性為 DateTimeKind.Local 的值,並將日期和時間 s 轉換成當地時間。 否則,它不會執行時區轉換,並傳回 DateTimeKind 屬性為 DateTimeKind.Unspecified 的值。

此多載會嘗試使用目前文化特性的格式慣例來剖析 s 。 目前的文化特性是由 CurrentCulture 屬性工作表示。 若要使用特定文化特性的格式慣例剖析字串,請呼叫 Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles) 多載。

此多載會嘗試使用 DateTimeStyles.AllowWhiteSpaces 樣式剖析 s

另請參閱

適用於

Parse(ReadOnlySpan<Char>, IFormatProvider)

將字元範圍剖析為值。

public:
 static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<DateTime>::Parse;
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As DateTime

參數

provider
IFormatProvider

傳回

DateTime

剖析 s 的結果。

實作

適用於

Parse(String, IFormatProvider)

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTime

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<DateTime>::Parse;
public static DateTime Parse (string s, IFormatProvider provider);
public static DateTime Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider) As DateTime

參數

s
String

字串,包含要轉換的日期和時間。 如需詳細資訊,請參閱要剖析的字串

provider
IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。 請參閱剖析和文化特性慣例

傳回

DateTime

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

實作

例外狀況

snull

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

範例

下列範例會使用 en-US、fr-FR 和 de-DE 文化特性的慣例來剖析日期字串的陣列。 它示範單一日期的字串表示可以不同文化特性的不同解譯。

using System;
using System.Globalization;

public class ParseDate
{
   public static void Main()
   {
      // Define cultures to be used to parse dates.
      CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"),
                                CultureInfo.CreateSpecificCulture("fr-FR"),
                                CultureInfo.CreateSpecificCulture("de-DE")};
      // Define string representations of a date to be parsed.
      string[] dateStrings = {"01/10/2009 7:34 PM",
                              "10.01.2009 19:34",
                              "10-1-2009 19:34" };
      // Parse dates using each culture.
      foreach (CultureInfo culture in cultures)
      {
         DateTime dateValue;
         Console.WriteLine("Attempted conversions using {0} culture.",
                           culture.Name);
         foreach (string dateString in dateStrings)
         {
            try {
               dateValue = DateTime.Parse(dateString, culture);
               Console.WriteLine("   Converted '{0}' to {1}.",
                                 dateString, dateValue.ToString("f", culture));
            }
            catch (FormatException) {
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.",
                                 dateString, culture.Name);
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output to the console:
//       Attempted conversions using en-US culture.
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
//       Attempted conversions using fr-FR culture.
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
//       Attempted conversions using de-DE culture.
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
open System
open System.Globalization

// Define cultures to be used to parse dates.
let cultures = 
    [ CultureInfo.CreateSpecificCulture "en-US"
      CultureInfo.CreateSpecificCulture "fr-FR"
      CultureInfo.CreateSpecificCulture "de-DE" ]

// Define string representations of a date to be parsed.
let dateStrings = 
    [ "01/10/2009 7:34 PM"
      "10.01.2009 19:34"
      "10-1-2009 19:34" ]

// Parse dates using each culture.
for culture in cultures do
    printfn $"Attempted conversions using {culture.Name} culture."
    for dateString in dateStrings do
        try
            let dateValue = DateTime.Parse(dateString, culture)
            printfn $"""   Converted '{dateString}' to {dateValue.ToString("f", culture)}."""
        with :? FormatException ->
            printfn $"   Unable to convert '{dateString}' for culture {culture.Name}." 
    printfn ""


// The example displays the following output to the console:
//       Attempted conversions using en-US culture.
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
//       Attempted conversions using fr-FR culture.
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
//       Attempted conversions using de-DE culture.
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
Imports System.Globalization

Module ParseDate
   Public Sub Main()
      ' Define cultures to be used to parse dates.
      Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _
                                       CultureInfo.CreateSpecificCulture("fr-FR"), _
                                       CultureInfo.CreateSpecificCulture("de-DE")}
      ' Define string representations of a date to be parsed.
      Dim dateStrings() As String = {"01/10/2009 7:34 PM", _
                                     "10.01.2009 19:34", _
                                     "10-1-2009 19:34" }
      ' Parse dates using each culture.
      For Each culture In cultures
         Dim dateValue As Date
         Console.WriteLine("Attempted conversions using {0} culture.", culture.Name)
         For Each dateString As String In dateStrings
            Try
               dateValue = Date.Parse(dateString, culture)
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 dateString, dateValue.ToString("f", culture))
            Catch e As FormatException
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", _
                                 dateString, culture.Name)
            End Try                                                
         Next
         Console.WriteLine()
      Next                                                                                     
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversions using en-US culture.
'          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
'          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'       
'       Attempted conversions using fr-FR culture.
'          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
'          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
'          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
'       
'       Attempted conversions using de-DE culture.
'          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
'          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
'          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.

備註

如果 s 包含時區資訊,這個方法會 DateTime Kind 傳回其 屬性為 DateTimeKind.Local 的值,並將日期和時間 s 轉換成當地時間。 否則,它不會執行時區轉換,並傳回 DateTime 其屬性為 DateTimeKind.Unspecified 的值 Kind

此多載會嘗試使用 DateTimeStyles.AllowWhiteSpaces 樣式剖析 s

另請參閱

適用於

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTime

public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member Parse : ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional provider As IFormatProvider = Nothing, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

參數

s
ReadOnlySpan<Char>

包含要剖析字串的記憶體範圍。 如需詳細資訊,請參閱要剖析的字串

provider
IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。 請參閱剖析和文化特性慣例

styles
DateTimeStyles

列舉值的位元組合,表示可以在 s 中出現使剖析作業成功,以及定義如何解譯剖析的日期與目前時區或目前日期之間關聯性的樣式項目。 一般會指定的值是 None

傳回

DateTime

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

例外狀況

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

styles 包含 DateTimeStyles 值的無效組合。 如需範例,請參閱 AssumeLocalAssumeUniversal

適用於

Parse(String, IFormatProvider, DateTimeStyles)

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTime

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider, System::Globalization::DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider provider, System.Globalization.DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider? provider, System.Globalization.DateTimeStyles styles);
static member Parse : string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider, styles As DateTimeStyles) As DateTime

參數

s
String

字串,包含要轉換的日期和時間。 如需詳細資訊,請參閱要剖析的字串

provider
IFormatProvider

物件,其提供關於 s 的特定文化特性格式資訊。 請參閱剖析和文化特性慣例

styles
DateTimeStyles

列舉值的位元組合,表示可以在 s 中出現使剖析作業成功,以及定義如何解譯剖析的日期與目前時區或目前日期之間關聯性的樣式項目。 一般會指定的值是 None

傳回

DateTime

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

例外狀況

snull

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

styles 包含 DateTimeStyles 值的無效組合。 如需範例,請參閱 AssumeLocalAssumeUniversal

範例

下列範例示範 Parse(String, IFormatProvider, DateTimeStyles) 方法,並顯示 Kind 結果 DateTime 值的 屬性值。

using System;
using System.Globalization;

public class ParseDateExample
{
   public static void Main()
   {
      string dateString;
      CultureInfo culture ;
      DateTimeStyles styles;
      DateTime result;

      // Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.",
                           dateString);
      }

      // Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }

      // Parse a date and time that is assumed to be local.
      // This time is five hours behind UTC. The local system's time zone is
      // eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00";
      styles = DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }

      // Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00";
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }

      // Assume a date and time string formatted for the fr-FR culture is the local
      // time and convert it to UTC.
      dateString = "2008-03-01 10:00";
      culture = CultureInfo.CreateSpecificCulture("fr-FR");
      styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }
   }
}
// The example displays the following output to the console:
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
//       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
//       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
//       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Parse a date and time with no styles.
    let dateString = "03/01/2009 10:00 AM"
    let culture = CultureInfo.CreateSpecificCulture "en-US"
    let styles = DateTimeStyles.None
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse the same date and time with the AssumeLocal style.
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse a date and time that is assumed to be local.
    // This time is five hours behind UTC. The local system's time zone is
    // eight hours behind UTC.
    let dateString = "2009/03/01T10:00:00-5:00"
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Attempt to convert a string in improper ISO 8601 format.
    let dateString = "03/01/2009T10:00:00-5:00"
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Assume a date and time string formatted for the fr-FR culture is the local
    // time and convert it to UTC.
    let dateString = "2008-03-01 10:00"
    let culture = CultureInfo.CreateSpecificCulture "fr-FR"
    let styles = DateTimeStyles.AdjustToUniversal ||| DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    0

// The example displays the following output to the console:
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
//       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
//       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
//       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
Imports System.Globalization

Module ParseDateExample
   Public Sub Main()
      Dim dateString As String  
      Dim culture As CultureInfo
      Dim styles As DateTimeStyles 
      Dim result As DateTime
      
      ' Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM"
      culture = CultureInfo.CreateSpecificCulture("en-US")
      styles = DateTimeStyles.None
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Parse a date and time that is assumed to be local.
      ' This time is five hours behind UTC. The local system's time zone is 
      ' eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00"
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00"
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      

      ' Assume a date and time string formatted for the fr-FR culture is the local 
      ' time and convert it to UTC.
      dateString = "2008-03-01 10:00"
      culture = CultureInfo.CreateSpecificCulture("fr-FR")
      styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
   End Sub
End Module
'
' The example displays the following output to the console:
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
'       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
'       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
'       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.

備註

這個方法多載會轉換 中的 s 日期和時間,並設定 KindDateTime 回值的 屬性,如下所示:

如果 時區轉換 Kind 屬性
s 不包含時區資訊。 無。 DateTimeKind.Unspecified
s 包含時區資訊。 到當地時區的時間 DateTimeKind.Local
s 包含時區資訊,並 styles 包含 DateTimeStyles.AdjustToUniversal 旗標。 以國際標準時間 (UTC) DateTimeKind.Utc
s 包含 Z 或 GMT 時區指示項,並 styles 包含 DateTimeStyles.RoundtripKind 無。 DateTimeKind.Utc

另請參閱

適用於