DateTime.Parse DateTime.Parse DateTime.Parse DateTime.Parse Method

定義

將日期和時間的字串表示,轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent.

多載

Parse(String) Parse(String) Parse(String) Parse(String)

使用目前執行緒文化特性的慣例,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

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

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles)

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

範例

呼叫的數個範例DateTime.Parse方法散佈整個備註這篇文章,並在個別的文件中的區段DateTime.Parse多載。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 內嵌程式碼執行器和測試區執行。Some C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Try.NET 內嵌程式碼執行器與 Playground 的當地時區是全球標準時間 (UTC)。The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. 這可能會影響示範 DateTimeDateTimeOffsetTimeZoneInfo 型別與其成員之範例的行為與輸出。This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

您也可以下載一組完整的DateTime.Parse中所包含的範例適用於 C# 的.NET Core 2.0 專案適用於 Visual Basic.NET Core 2.0 專案,從dotnet /範例 GitHub 儲存機制You can also download a complete set of DateTime.Parse examples, which are included in a .NET Core 2.0 project for C# and a .NET Core 2.0 project for Visual Basic, from the dotnet/samples GitHub repository.

備註

本節內容:In this section:

我呼叫的方法?Which method do I call?

To CallCall
使用目前文化特性的慣例來剖析日期和時間的字串。Parse a date and time string by using the conventions of the current culture. Parse(String) 多載Parse(String) overload
使用特定文化特性的慣例,以剖析日期和時間的字串。Parse a date and time string by using the conventions of a specific culture. Parse(String, IFormatProvider) 多載 (請參閱剖析和文化習俗)Parse(String, IFormatProvider) overload (see Parsing and Cultural Conventions)
剖析日期和時間的字串使用特殊的樣式項目 (例如空白字元或不含空白)。Parse a date and time string with special style elements (such as white space or no white space). Parse(String, IFormatProvider, DateTimeStyles) 多載Parse(String, IFormatProvider, DateTimeStyles) overload
剖析日期和時間的字串必須以特定格式。Parse a date and time string that must be in a particular format. DateTime.ParseExactDateTime.TryParseExactDateTime.ParseExact or DateTime.TryParseExact
剖析日期和時間的字串,並執行轉換為 UTC 或本地時間。Parse a date and time string and perform a conversion to UTC or local time. Parse(String, IFormatProvider, DateTimeStyles) 多載Parse(String, IFormatProvider, DateTimeStyles) overload
剖析日期和時間的字串,而不需要處理的例外狀況。Parse a date and time string without handling exceptions. DateTime.TryParse 方法DateTime.TryParse method
還原執行格式化作業 (來回) 建立的日期和時間值。Restore (round-trip) a date and time value created by a formatting operation. 傳遞的"o"或"r"標準格式字串ToString(String)方法,並呼叫Parse(String, IFormatProvider, DateTimeStyles)多載 DateTimeStyles.RoundtripKindPass the "o" or "r" standard format string to the ToString(String) method, and call the Parse(String, IFormatProvider, DateTimeStyles) overload with DateTimeStyles.RoundtripKind
剖析固定格式的日期和時間字串跨電腦 (和可能的文化特性) 的界限。Parse a date and time string in a fixed format across machine (and possibly cultural) boundaries. DateTime.ParseExactDateTime.TryParseExact方法DateTime.ParseExact or DateTime.TryParseExact method

要剖析的字串The string to parse

Parse方法會嘗試將日期和時間值的字串表示轉換成其DateTime相等。The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. 它會嘗試將輸入的字串完全剖析而不擲回FormatException例外狀況。It tries to parse the input string completely without throwing a FormatException exception.

重要

如果剖析作業失敗,因為無法辨識的字串格式,所以Parse方法會擲回FormatException,而TryParse方法會傳回falseIf the parsing operation fails because of an unrecognized string format, the Parse method throws a FormatException, whereas the TryParse method returns false. 因為例外狀況處理可能很耗費資源,您應該使用Parse當預期在剖析作業成功,因為輸入的來源是受信任。Because exception handling can be expensive, you should use Parse when the parsing operation is expected to succeed because the input source is trusted. TryParse 當剖析失敗有可能,特別是因為輸入的來源不受信任,或您有合理的預設值來取代未成功剖析的字串,則會是偏好。TryParse is preferable when parsing failures are likely, particularly because an input source is not trusted, or you have reasonable default values to substitute for strings that do not parse successfully.

要剖析的字串可以採用任何下列形式:The string to be parsed can take any of the following forms:

  • 含有日期和時間元件的字串。A string with a date and a time component.

  • 含日期,但沒有時間部分的字串。A string with a date but no time component. 如果時間元件不存在,則方法會假設午夜 12:00。If the time component is absent, the method assumes 12:00 midnight. 如果日期元件有兩位數年份,則會轉換成根據年份Calendar.TwoDigitYearMax目前的文化特性的現行曆法或指定的文化特性的現行曆法的 (如果您使用多載具有非 nullprovider引數)。If the date component has a two-digit year, it is converted to a year based on the Calendar.TwoDigitYearMax of the current culture's current calendar or the specified culture's current calendar (if you use an overload with a non-null provider argument).

  • 字串,包含只月份和年份的日期元件,但沒有日元件。A string with a date component that includes only the month and the year but no day component. 此方法會假設每月的第一天。The method assumes the first day of the month.

  • 字串,包含每月和日的日期元件,但沒有年元件。A string with a date component that includes only the month and the day but no year component. 此方法會假設目前的年份。The method assumes the current year.

  • 包含時間但不含日期項目的字串。A string with a time but no date component. 此方法假設目前的日期,除非您呼叫Parse(String, IFormatProvider, DateTimeStyles)多載,並包含DateTimeStyles.NoCurrentDateDefaultstyles引數,在其中案例的方法會假設年 1 月 1 日的日期以 0001。The method assumes the current date unless you call the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.

  • 字串,具有時間元件,其中包含在一小時和 AM/PM 指示項,與任何日期元件。A string with a time component that includes only the hour and an AM/PM designator, with no date component. 此方法會假設目前的日期和時間與沒有分鐘和不含秒數。The method assumes the current date and a time with no minutes and no seconds. 您可以變更此行為,藉由呼叫Parse(String, IFormatProvider, DateTimeStyles)多載,並包含DateTimeStyles.NoCurrentDateDefaultstyles引數,在其中案例的方法會假設年 1 月 1 日的日期以 0001。You can change this behavior by calling the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.

  • 字串,包含時區資訊,並符合 ISO 8601 標準。A string that includes time zone information and conforms to ISO 8601. 在下列範例中,第一個字串將指定 Coordinated Universal Time (UTC) 和第二個指定的時間相差七個小時的時區中早於 UTC:In the following examples, the first string designates Coordinated Universal Time (UTC), and the second designates the time in a time zone that's seven hours earlier than UTC:

    "2008-11-01T19:35:00.0000000Z""2008-11-01T19:35:00.0000000Z"
    "2008-11-01T19:35:00.0000000-07:00""2008-11-01T19:35:00.0000000-07:00"

  • 字串,包含 GMT 指示項,並符合 RFC 1123 時間格式;例如:A string that includes the GMT designator and conforms to the RFC 1123 time format; for example:

    「 2008 年 11 月 01 日,星期六格林威治時間 19:35:00""Sat, 01 Nov 2008 19:35:00 GMT"

  • 字串,其中包含的日期和時間的時區位移的資訊; 以及例如:A string that includes the date and time along with time zone offset information; for example:

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

下列範例會使用目前的文化特性,在此案例中是 EN-US 文化特性的格式化慣例來剖析中每種格式的字串:The following example parses strings in each of these formats by using the formatting conventions of the current culture, which in this case is the en-US culture:

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


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方法已成功剖析字串。If the input string represents a leap day in a leap year in the calendar used by the parsing method (see Parsing and cultural conventions), the Parse method parses the string successfully. 如果輸入的字串代表為閏日在非為閏年,則方法會擲回FormatExceptionIf the input string represents a leap day in a non-leap year, the method throws a FormatException.

因為Parse方法會嘗試剖析日期字串表示,並使用目前或指定的文化特性,嘗試將字串剖析跨不同的文化特性的格式化規則的時間可能會失敗。Because the Parse method tries to parse the string representation of a date and time by using the formatting rules of the current or a specified culture, trying to parse a string across different cultures can fail. 若要剖析的特定日期和時間格式,在不同的地區設定,使用其中一個多載DateTime.ParseExact方法,並提供格式規範。To parse a specific date and time format across different locales, use one of the overloads of the DateTime.ParseExact method and provide a format specifier.

剖析和文化特性的慣例Parsing and cultural conventions

所有多載Parse方法會區分文化特性除非要剖析的字串 (表示s下表) 符合 ISO 8601 模式。All overloads of the Parse method are culture-sensitive unless the string to be parsed (which is represented by s in the following table) conforms to the ISO 8601 pattern. 剖析作業所使用的格式設定資訊中DateTimeFormatInfo物件衍生,如下所示:The parsing operation uses the formatting information in a DateTimeFormatInfo object that is derived as follows:

重要

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

如果您呼叫If you call providerAnd provider is 格式設定資訊衍生自Formatting information is derived from
Parse(String) - 目前執行緒文化特性 (DateTimeFormatInfo.CurrentInfo屬性)The current thread culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) ADateTimeFormatInfo物件a DateTimeFormatInfo object 指定DateTimeFormatInfo物件The specified DateTimeFormatInfo object
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) null 目前執行緒文化特性 (DateTimeFormatInfo.CurrentInfo屬性)The current thread culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) ACultureInfo物件a CultureInfo object CultureInfo.DateTimeFormat 屬性The CultureInfo.DateTimeFormat property
Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) 自訂IFormatProvider實作Custom IFormatProvider implementation IFormatProvider.GetFormat 方法The IFormatProvider.GetFormat method

當格式化資訊衍生自DateTimeFormatInfo物件,DateTimeFormatInfo.Calendar屬性會定義剖析作業中所使用的行事曆。When formatting information is derived from a DateTimeFormatInfo object, the DateTimeFormatInfo.Calendar property defines the calendar used in the parsing operation.

如果您使用來剖析日期和時間字串DateTimeFormatInfo物件以自訂不同於標準的文化特性的設定,請使用ParseExact方法,而非Parse方法,以提升成功轉換的機率。If you parse a date and time string by using a DateTimeFormatInfo object with customized settings that are different from those of a standard culture, use the ParseExact method instead of the Parse method to improve the chances for a successful conversion. 非標準日期和時間字串可以是複雜且很難剖析。A non-standard date and time string can be complicated and difficult to parse. Parse方法會嘗試剖析的字串與數個隱含的剖析模式,其中都可能會失敗。The Parse method tries to parse a string with several implicit parse patterns, all of which might fail. 相反地,ParseExact方法需要您明確地指定一或多個實際的剖析模式可能會成功。In contrast, the ParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. 如需詳細資訊,請參閱中的 < DateTimeFormatInfo 和動態資料 > 一節DateTimeFormatInfo主題。For more information, see the "DateTimeFormatInfo and Dynamic Data" section in the DateTimeFormatInfo topic.

重要

請注意特定文化特性的格式化慣例是動態的而且可能會受到變更影響。Note that the formatting conventions for a particular culture are dynamic and can be subject to change. 這表示,依賴預設值 (目前) 的文化特性或格式設定慣例的剖析作業指定IFormatProvider代表文化特性而異的文化特性以外的物件可能會發生下列任一項非預期地失敗:This means that parsing operations that depend on the formatting conventions of the default (current) culture or that specify an IFormatProvider object that represents a culture other than the invariant culture can unexpectedly fail if any of the following occurs:

  • .NET Framework 的或現有的.NET framework 版本的更新結果的主要或次要版本之間已經變更的特定文化特性的資料。The culture-specific data has changed between major or minor versions of the .NET Framework or as the result of an update to the existing version of the .NET Framework.
  • 特定文化特性的資料會反映使用者喜好設定,電腦或工作階段而有所不同。The culture-specific data reflects user preferences, which can vary from machine to machine or session to session.
  • 特定文化特性的資料代表取代的文化特性來覆寫標準文化特性或自訂的文化特性的設定。The culture-specific data represents a replacement culture that overrides the settings of a standard culture or a custom culture.

若要避免在剖析日期和時間的字串與文化特性的資料變更相關聯的問題,您就可以使用文化特性而異,來剖析日期和時間字串,或您可以呼叫ParseExactTryParseExact方法並指定確切的格式要剖析的字串。To prevent the difficulties in parsing data and time strings that are associated with changes in cultural data, you can parse date and time strings by using the invariant culture, or you can call the ParseExact or TryParseExact method and specify the exact format of the string to be parsed. 如果您要序列化和還原序列化日期和時間資料,您可以使用的格式化慣例的文化特性而異,或您可以序列化和還原序列化DateTime以二進位格式的值。If you are serializing and deserializing date and time data, you can either use the formatting conventions of the invariant culture, or you can serialize and deserialize the DateTime value in a binary format.

如需詳細資訊,請參閱 「 動態的文化特性資料 」 一節CultureInfo主題和 「 持續性的 DateTime 值 」 一節中DateTime主題。For more information see the "Dynamic culture data" section in the CultureInfo topic and the "Persisting DateTime values" section in the DateTime topic.

剖析和樣式項目Parsing and style elements

所有Parse多載略過前置、 內部或尾端空格字元,輸入字串中的 (表示s下表中)。All Parse overloads ignore leading, inner, or trailing white-space characters in the input string (which is represented by s in the following table). 日期和時間可以是一組的開頭和尾端數字符號字元 ("#",U + 0023),而且必須尾隨一或多個 NULL 字元 (U + 0000)。The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ("#", U+0023), and can be trailed with one or more NULL characters (U+0000).

颾魤 ㄛParse(String, IFormatProvider, DateTimeStyles)多載具有styles參數所組成的一或多個成員DateTimeStyles列舉型別。In addition, the Parse(String, IFormatProvider, DateTimeStyles) overload has a styles parameter that consists of one or more members of the DateTimeStyles enumeration. 此參數會定義如何s應解譯和剖析作業應該如何將轉換s日期和時間。This parameter defines how s should be interpreted and how the parse operation should convert s to a date and time. 下表描述每個效果DateTimeStyles在剖析作業的成員。The following table describes the effect of each DateTimeStyles member on the parse operation.

DateTimeStyles 成員DateTimeStyles member 在轉換的效果Effect on conversion
AdjustToUniversal 剖析s而且,如果有需要,將它轉換成 UTC,,如下所示:Parses s and, if necessary, converts it to UTC, as follows:

-如果s包含時區時差,或者如果s不包含時區資訊,但styles包括AssumeLocal旗標,這個方法會剖析字串,呼叫ToUniversalTime轉換傳回DateTime值UTC,並設定Kind屬性設DateTimeKind.Utc- If s includes a time zone offset, or if s contains no time zone information but styles includes the AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind.Utc.
-如果s表示它代表 UTC,或者如果s不包含時區資訊,但styles包括AssumeUniversal旗標,方法剖析字串,會執行任何時區轉換對傳回DateTime值,並設定Kind屬性設DateTimeKind.Utc- If s indicates that it represents UTC, or if s does not contain time zone information but styles includes the AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind.Utc.
-在所有其他的情況下,此旗標會有任何作用。- In all other cases, the flag has no effect.
AllowInnerWhite 這個值會被忽略。This value is ignored. 內部空白字元一律允許的日期和時間項目中sInner white space is always permitted in the date and time elements of s.
AllowLeadingWhite 這個值會被忽略。This value is ignored. 中的日期和時間項目一律允許前置空白字元sLeading white space is always permitted in the date and time elements of s.
AllowTrailingWhite 這個值會被忽略。This value is ignored. 中的日期和時間項目一律允許尾端泛空白字元sTrailing white space is always permitted in the date and time elements of s.
AllowWhiteSpaces 指定s可能包含前置、 內部和尾端空白字元。Specifies that s may contain leading, inner, and trailing white spaces. 這是預設行為。This is the default behavior. 它不能覆寫透過提供更具限制性DateTimeStyles列舉值,例如NoneIt cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value such as None.
AssumeLocal 指定當s缺少會假設任何時區資訊時,本地時間。Specifies that if s lacks any time zone information, local time is assumed. 除非AdjustToUniversal旗標已存在,Kind屬性傳回的DateTime值設定為DateTimeKind.LocalUnless the AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.
AssumeUniversal 指定當s缺少會假設任何時區資訊,UTC。Specifies that if s lacks any time zone information, UTC is assumed. 除非AdjustToUniversal旗標存在,則方法會將轉換傳回DateTime值與 UTC 於當地時間和設定其Kind屬性設DateTimeKind.LocalUnless the AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.
None 雖然有效,但會忽略此值。Although valid, this value is ignored.
RoundtripKind 針對包含時區資訊的字串,會嘗試防止日期和時間字串轉換成DateTime值,表示本地時間,和其Kind屬性設定為DateTimeKind.LocalFor strings that contain time zone information, tries to prevent the conversion of a date and time string to a DateTime value that represents a local time with its Kind property set to DateTimeKind.Local. 一般而言,這類字串由呼叫DateTime.ToString(String)方法並使用"o"、"r"或"u"標準格式規範。Typically, such a string is created by calling the DateTime.ToString(String) method and by using the "o", "r", or "u" standard format specifier.

傳回值和 DateTime.KindThe return value and DateTime.Kind

DateTime.Parse多載會傳回DateTimeKind屬性包含時區資訊。The DateTime.Parse overloads return a DateTime value whose Kind property includes time zone information. 它可能表示,時間:It can indicate that the time is:

一般而言,Parse方法會傳回DateTime物件,其Kind屬性是DateTimeKind.UnspecifiedGenerally, the Parse method returns a DateTime object whose Kind property is DateTimeKind.Unspecified. 不過,Parse方法也可能會在執行時區轉換,並將值Kind屬性以不同的方式,根據的值sstyles參數:However, the Parse method may also perform time zone conversion and set the value of the Kind property differently, depending on the values of the s and styles parameters:

如果If 時區轉換Time zone conversion 類型屬性Kind property
s 包含時區資訊。s contains time zone information. 日期和時間是以當地時區轉換為的時間。The date and time is converted to the time in the local time zone. DateTimeKind.Local
s 包含時區資訊,以及styles包含AdjustToUniversal旗標。s contains time zone information, and styles includes the AdjustToUniversal flag. 日期和時間會轉換為 Coordinated Universal Time (UTC)。The date and time is converted to Coordinated Universal Time (UTC). DateTimeKind.Utc
s 包含 Z 或 GMT 的時區指示項,並styles包含RoundtripKind旗標。s contains the Z or GMT time zone designator, and styles includes the RoundtripKind flag. 日期和時間視為 UTC。The date and time are interpreted as UTC. DateTimeKind.Utc

下列範例會將日期字串,包含以當地時區的時區資訊的時間:The following example converts date strings that contain time zone information to the time in the local time zone:

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                                             
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                                             

您也可以保留的日期和時間的值Kind屬性的格式設定和使用剖析作業期間DateTimeStyles.RoundtripKind旗標。You can also preserve the value of a date and time's Kind property during a formatting and parsing operation by using the DateTimeStyles.RoundtripKind flag. 下列範例說明如何RoundtripKind旗標會影響剖析的作業上DateTime使用"o"、"r"或"u"格式規範會轉換為字串的值。The following example illustrates how the RoundtripKind flag affects the parsing operation on DateTime values that are converted to strings by using the "o", "r", or "u" format specifier.

   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.      
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) Parse(String) Parse(String) Parse(String)

使用目前執行緒文化特性的慣例,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

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 String String String

字串,包含要轉換的日期和時間。A string that contains a date and time to convert. 如需詳細資訊,請參閱要剖析的字串See The string to parse for more information.

傳回

物件,與 s 中包含的日期和時間相等。An object that is equivalent to the date and time contained in s.

例外狀況

s 不包含日期與時間的有效字串表示。s does not contain a valid string representation of a date and time.

備註

如果s包含時區資訊,這個方法會傳回DateTimeKind屬性是DateTimeKind.Local,並將轉換的日期和時間在s為當地時間。If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. 否則,它會執行任何時區轉換,並傳回DateTimeKind屬性是DateTimeKind.UnspecifiedOtherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

這個多載會嘗試剖析s使用目前文化特性的格式化慣例。This overload attempts to parse s by using the formatting conventions of the current culture. 目前的文化特性會由CurrentCulture屬性。The current culture is indicated by the CurrentCulture property. 若要使用之特定文化特性的格式化慣例將字串剖析,呼叫Parse(String, IFormatProvider)Parse(String, IFormatProvider, DateTimeStyles)多載。To parse a string using the formatting conventions of a specific culture, call the Parse(String, IFormatProvider) or the Parse(String, IFormatProvider, DateTimeStyles) overloads.

這個多載會嘗試剖析s使用DateTimeStyles.AllowWhiteSpaces樣式。This overload attempts to parse s by using DateTimeStyles.AllowWhiteSpaces style.

範例Example

下列範例會剖析由數個日期和時間值的字串表示法:The following example parses the string representation of several date and time values by:

  • 使用預設的格式提供者,提供用來產生輸出範例中的電腦的目前執行緒文化特性的格式化慣例。Using the default format provider, which provides the formatting conventions of the current thread culture of the computer used to produce the example output. 此範例的輸出會反映 EN-US 文化特性的格式化慣例。The output from this example reflects the formatting conventions of the en-US culture.

  • 使用預設樣式值,亦即AllowWhiteSpacesUsing the default style value, which is AllowWhiteSpaces.

它會處理FormatException當方法嘗試使用其他文化特性剖析的日期和時間的字串表示時,會擲回的例外狀況的格式化慣例。It handles the FormatException exception that is thrown when the method tries to parse the string representation of a date and time by using some other culture's formatting conventions. 它也會示範如何成功地剖析日期和時間值,不會使用目前執行緒文化特性的格式化慣例。It also shows how to successfully parse a date and time value that does not use the formatting conventions of the current thread culture.

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.
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.
另請參閱

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

public:
 static DateTime Parse(System::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 String String String

字串,包含要轉換的日期和時間。A string that contains a date and time to convert. 如需詳細資訊,請參閱要剖析的字串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。An object that supplies culture-specific format information about s. 請參閱剖析和文化特性慣例See Parsing and cultural conventions

傳回

物件,與 s 中包含的日期和時間相等,如 provider 所指定。An object that is equivalent to the date and time contained in s as specified by provider.

例外狀況

s 不包含日期與時間的有效字串表示。s does not contain a valid string representation of a date and time.

備註

如果s包含時區資訊,這個方法會傳回DateTimeKind屬性是DateTimeKind.Local,並將轉換的日期和時間在s為當地時間。If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. 否則,它會執行任何時區轉換,並傳回DateTimeKind屬性是DateTimeKind.UnspecifiedOtherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

這個多載會嘗試剖析s使用DateTimeStyles.AllowWhiteSpaces樣式。This overload attempts to parse s by using the DateTimeStyles.AllowWhiteSpaces style.

範例Example

下列範例會使用 EN-US、 FR-FR 和 DE-DE 文化特性的慣例來剖析日期字串的陣列。The following example parses an array of date strings by using the conventions of the en-US, fr-FR, and de-DE cultures. 它會示範單一日期的字串表示可以以不同方式解譯跨不同的文化特性。It demonstrates that the string representations of a single date can be interpreted differently across different cultures.

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.
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.
另請參閱

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

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = null, 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 = null, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

參數

s
ReadOnlySpan<Char>

包含要剖析字串的記憶體範圍。The memory span that contains the string to parse. 如需詳細資訊,請參閱要剖析的字串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。An object that supplies culture-specific format information about s. 請參閱剖析和文化特性慣例See Parsing and cultural conventions

styles
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

列舉值的位元組合,表示可以在 s 中出現使剖析作業成功,以及定義如何解譯剖析的日期與目前時區或目前日期之間關聯性的樣式項目。A bitwise combination of the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed, and that defines how to interpret the parsed date in relation to the current time zone or the current date. 一般會指定的值是 NoneA typical value to specify is None.

傳回

物件,與 s 中包含的日期和時間相等,如 providerstyles 所指定。An object that is equivalent to the date and time contained in s, as specified by provider and styles.

例外狀況

s 不包含日期與時間的有效字串表示。s does not contain a valid string representation of a date and time.

styles 包含 DateTimeStyles 值的無效組合。styles contains an invalid combination of DateTimeStyles values. 如需範例,請參閱 AssumeLocalAssumeUniversalFor example, both AssumeLocal and AssumeUniversal.

Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles)

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

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);
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 String String String

字串,包含要轉換的日期和時間。A string that contains a date and time to convert. 如需詳細資訊,請參閱要剖析的字串See The string to parse for more information.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s. 請參閱剖析和文化特性慣例See Parsing and cultural conventions

styles
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

列舉值的位元組合,表示可以在 s 中出現使剖析作業成功,以及定義如何解譯剖析的日期與目前時區或目前日期之間關聯性的樣式項目。A bitwise combination of the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed, and that defines how to interpret the parsed date in relation to the current time zone or the current date. 一般會指定的值是 NoneA typical value to specify is None.

傳回

物件,與 s 中包含的日期和時間相等,如 providerstyles 所指定。An object that is equivalent to the date and time contained in s, as specified by provider and styles.

例外狀況

s 不包含日期與時間的有效字串表示。s does not contain a valid string representation of a date and time.

styles 包含 DateTimeStyles 值的無效組合。styles contains an invalid combination of DateTimeStyles values. 如需範例,請參閱 AssumeLocalAssumeUniversalFor example, both AssumeLocal and AssumeUniversal.

備註

這個方法多載會將轉換的日期和時間s,並設定Kind屬性傳回之DateTime值,如下所示:This method overload converts the date and time in s and sets the Kind property of the returned DateTime value as follows:

如果If 時區轉換Time zone conversion 類型屬性Kind property
s 不包含時區資訊。s contains no time zone information. 無。None. DateTimeKind.Unspecified
s 包含時區資訊。s contains time zone information. 當地時區的時間To the time in the local time zone DateTimeKind.Local
s 包含時區資訊和 ' 樣式包含DateTimeStyles.AdjustToUniversal旗標。s contains time zone information, and `styles includes the DateTimeStyles.AdjustToUniversal flag. 為國際標準時間 (UTC)To Coordinated Universal Time (UTC) DateTimeKind.Utc
s 包含 Z 或 GMT 的時區指示項,並styles包含DateTimeStyles.RoundtripKinds contains the Z or GMT time zone designator, and styles includes the DateTimeStyles.RoundtripKind. 無。None. Utc

範例Example

下列範例示範Parse(String, IFormatProvider, DateTimeStyles)方法,並顯示的值Kind屬性產生DateTime值。The following example demonstrates the Parse(String, IFormatProvider, DateTimeStyles) method and displays the value of the Kind property of the resulting DateTime values.

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.
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.
另請參閱

適用於