DateTime.ParseExact 方法

定義

將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match a specified format exactly or an exception is thrown.

多載

ParseExact(String, String, IFormatProvider)

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

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

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match the specified format exactly or an exception is thrown.

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

使用指定格式、特定文化特性格式資訊以及樣式的陣列,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match the specified format exactly or an exception is thrown.

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。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.

ParseExact(String, String, IFormatProvider)

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

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

參數

s
String

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

format
String

格式規範,其定義 s 所需的格式。A format specifier that defines the required format of s. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

provider
IFormatProvider

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

傳回

DateTime

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

例外狀況

sformatnulls or format is null.

sformat 為空字串。s or format is an empty string.

-或--or- s 不包含與 format 中所指定之模式對應的日期和時間。s does not contain a date and time that corresponds to the pattern specified in format.

-或--or- 小時元件和 s 中的 AM/PM 指示項不相符。The hour component and the AM/PM designator in s do not agree.

範例

下列範例會示範 ParseExact 方法。The following example demonstrates the ParseExact method.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString, format;
      DateTime result;
      CultureInfo provider = CultureInfo.InvariantCulture;

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

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

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

      // Parse date and time with offset but without offset's minutes.
      // Should throw a FormatException because "zzz" specifier requires leading
      // zero in hours.
      dateString = "Sun 15 Jun 2008 8:30 AM -06";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      dateString = "15/06/2008 08:30";
      format = "g";
      provider = new CultureInfo("fr-FR");
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse a date that includes seconds and milliseconds
      // by using the French (France) and invariant cultures.
      dateString = "18/08/2015 06:30:15.006542";
      format = "dd/MM/yyyy HH:mm:ss.ffffff";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }
   }
}
// The example displays the following output:
//       06/15/2008 converts to 6/15/2008 12:00:00 AM.
//       6/15/2008 is not in the correct format.
//       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
//       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
//       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
//       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateString, format As String  
      Dim result As Date
      Dim provider As CultureInfo = CultureInfo.InvariantCulture

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

      ' Parse date-only value without leading zero in month using "d" format.
      ' Should throw a FormatException because standard short date pattern of 
      ' invariant culture requires two-digit month.
      dateString = "6/15/2008"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse date and time with custom specifier.
      dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
      format = "ddd dd MMM yyyy h:mm tt zzz"        
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse date and time with offset but without offset's minutes.
      ' Should throw a FormatException because "zzz" specifier requires leading  
      ' zero in hours.
      dateString = "Sun 15 Jun 2008 8:30 AM -06"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse a date string using the French (France) culture.
      dateString = "15/06/2008 08:30"
      format = "g"
      provider = New CultureInfo("fr-FR")
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try

      ' Parse a date that includes seconds and milliseconds
      ' by using the French (France) and invariant cultures.
      dateString = "18/08/2015 06:30:15.006542"
      format = "dd/MM/yyyy HH:mm:ss.ffffff"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try
   End Sub
End Module
' The example displays the following output:
'       06/15/2008 converts to 6/15/2008 12:00:00 AM.
'       6/15/2008 is not in the correct format.
'       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
'       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
'       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
'       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.

備註

DateTime.ParseExact(String, String, IFormatProvider)方法會剖析日期的字串表示,其格式必須是參數所定義的格式 formatThe DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter. 它也需要 <Date> <Time> 日期和時間的字串表示的和專案以指定的順序顯示 format ,而 s 不是允許的空白字元 formatIt also requires that the <Date> and <Time> elements of the string representation of a date and time appear in the order specified by format, and that s have no white space other than that permitted by format. 如果 format 定義的日期沒有時間元素,而且剖析作業成功,則產生的 DateTime 值會是午夜 (00:00:00) 。If format defines a date with no time element and the parse operation succeeds, the resulting DateTime value has a time of midnight (00:00:00). 如果 format 定義的時間沒有日期元素,而且剖析作業成功,則產生的 DateTime 值會是的日期 DateTime.Now.DateIf format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

如果不 s 代表特定時區的時間,而且剖析作業成功,則 Kind 傳回值的屬性 DateTimeDateTimeKind.UnspecifiedIf s does not represent a time in a particular time zone and the parse operation succeeds, the Kind property of the returned DateTime value is DateTimeKind.Unspecified. 如果 s 確實代表特定時區的時間,並允許時區 format 資訊存在 (例如,如果 format 等於 "o"、"r" 或 "u" 標準格式規範,或者如果它包含 "z"、"zz" 或 "zzz" 自訂格式規範) ,則 Kind 傳回值的屬性 DateTimeDateTimeKind.LocalIf s does represent the time in a particular time zone and format allows time zone information to be present (for example, if format is equal to the "o", "r", or "u" standard format specifiers, or if it contains the "z", "zz", or "zzz" custom format specifiers), the Kind property of the returned DateTime value is DateTimeKind.Local.

format參數是包含單一標準格式規範的字串,或是定義所需格式的一或多個自訂格式規範 sThe format parameter is a string that contains either a single standard format specifier, or one or more custom format specifiers that define the required format of s. 如需有效格式化程式碼的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串For details about valid formatting codes, see Standard Date and Time Format Strings or Custom Date and Time Format Strings.

注意

如果 format 是不包含日期或時間分隔符號 ((例如 ">yyyymmddhhmm" ) )的自訂格式模式,請針對參數使用不因文化特性而異, provider 並使用每個自訂格式規範的最寬形式。If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. 例如,如果您想要以格式模式指定時間,請指定較寬的表單 "HH",而不是較窄的格式 "H"。For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".

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

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

給呼叫者的注意事項

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

另請參閱

適用於

產品 推出的版本

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

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match the specified format exactly or an exception is thrown.

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

參數

s
ReadOnlySpan<Char>

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

format
ReadOnlySpan<Char>

包含字元的範圍,其表示定義 s 所需格式的格式規範。A span containing the characters that represent a format specifier that defines the required format of s.

provider
IFormatProvider

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

style
DateTimeStyles

列舉值的位元組合,提供有關 s、可以出現在 s 中的樣式項目,或是從 s 轉換成 DateTime 值的詳細資訊。A bitwise combination of the enumeration values that provides additional information about s, about style elements that may be present in s, or about the conversion from s to a DateTime value. 一般會指定的值是 NoneA typical value to specify is None.

傳回

DateTime

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

適用於

產品 推出的版本

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

使用指定格式、特定文化特性格式資訊以及樣式的陣列,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

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

參數

s
ReadOnlySpan<Char>

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

formats
String[]

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

provider
IFormatProvider

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

style
DateTimeStyles

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

傳回

DateTime

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

適用於

產品 推出的版本

ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match the specified format exactly or an exception is thrown.

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

參數

s
String

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

format
String

格式規範,其定義 s 所需的格式。A format specifier that defines the required format of s. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

provider
IFormatProvider

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

style
DateTimeStyles

列舉值的位元組合,提供有關 s、可以出現在 s 中的樣式項目,或是從 s 轉換成 DateTime 值的詳細資訊。A bitwise combination of the enumeration values that provides additional information about s, about style elements that may be present in s, or about the conversion from s to a DateTime value. 一般會指定的值是 NoneA typical value to specify is None.

傳回

DateTime

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

例外狀況

sformatnulls or format is null.

sformat 為空字串。s or format is an empty string.

-或--or- s 不包含與 format 中所指定之模式對應的日期和時間。s does not contain a date and time that corresponds to the pattern specified in format.

-或--or- 小時元件和 s 中的 AM/PM 指示項不相符。The hour component and the AM/PM designator in s do not agree.

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

範例

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

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo enUS = new CultureInfo("en-US");
      string dateString;
      DateTime dateValue;

      // Parse date with no style flags.
      dateString = " 5/01/2009 8:30 AM";
      try {
         dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      // Allow a leading space in the date string.
      try {
         dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }

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

      // Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00";
      try {
         dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      // Allow a leading space in the date string.
      try {
         dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS,
                                     DateTimeStyles.AdjustToUniversal);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }

      // Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z";
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                                     DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                                     DateTimeStyles.RoundtripKind);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
   }
}
// The example displays the following output:
//    ' 5/01/2009 8:30 AM' is not in an acceptable format.
//    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
//    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
//    '5/01/2009 09:00' is not in an acceptable format.
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).
Imports System.Globalization

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

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

備註

DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles)方法會剖析日期的字串表示,這必須是參數所定義的格式 formatThe DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method parses the string representation of a date, which must be in a format defined by the format parameter. 它也要求中的日期和時間元素必須 s 以所指定的順序出現 formatIt also requires that the date and time elements in s appear in the order specified by format. 如果不 s 符合參數的模式 format ,且參數定義了任何變異 style ,則方法會擲回 FormatExceptionIf s does not match the pattern of the format parameter, with any variations defined by the style parameter, the method throws a FormatException. 相反地,方法會使用 DateTime.Parse(String, IFormatProvider, DateTimeStyles) 格式提供者物件所辨識的任何格式,來剖析日期的字串表示 DateTimeFormatInfoIn contrast, the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method parses the string representation of a date in any one of the formats recognized by the format provider's DateTimeFormatInfo object. DateTime.Parse(String, IFormatProvider, DateTimeStyles)方法也可讓中的日期和時間元素以 s 任何順序出現。The DateTime.Parse(String, IFormatProvider, DateTimeStyles) method also allows the date and time elements in s to appear in any order.

如果 s 參數只包含時間且沒有日期,除非參數包含旗標,否則會使用目前的日期, style 在此 DateTimeStyles.NoCurrentDateDefault 情況下,會使用預設的日期 (DateTime.Date.MinValue) 。If the s parameter contains only a time and no date, the current date is used unless the style parameter includes the DateTimeStyles.NoCurrentDateDefault flag, in which case the default date (DateTime.Date.MinValue) is used. 如果 s 參數只包含日期而沒有時間,則會使用午夜 (00:00:00) 。If the s parameter contains only a date and no time, midnight (00:00:00) is used. style參數也會決定參數是否 s 可以包含前置、內部或尾端空白字元。The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters.

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

format參數會定義參數的必要模式 sThe format parameter defines the required pattern of the s parameter. 它可以由 自訂日期和時間格式字串 資料表中的一或多個自訂格式規範組成,或從 標準日期和時間格式字串 資料表中識別預先定義模式的單一標準格式規範。It can consist of either one or more custom format specifiers from the Custom Date and Time Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard Date and Time Format Strings table.

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

注意

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

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

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

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

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

給呼叫者的注意事項

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

另請參閱

適用於

產品 推出的版本

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

public:
 static DateTime ParseExact(System::String ^ s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style);
public static DateTime ParseExact (string s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style);
public static DateTime ParseExact (string s, string[] formats, IFormatProvider? provider, System.Globalization.DateTimeStyles style);
static member ParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function ParseExact (s As String, formats As String(), provider As IFormatProvider, style As DateTimeStyles) As DateTime

參數

s
String

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

formats
String[]

s 允許的格式陣列。An array of allowable formats of s. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

provider
IFormatProvider

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

style
DateTimeStyles

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

傳回

DateTime

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

例外狀況

sformatsnulls or formats is null.

s 為空字串。s is an empty string.

-或--or- formats 的項目為空字串。an element of formats is an empty string.

-或--or- s 不包含對應 formats 任何項目的日期和時間。s does not contain a date and time that corresponds to any element of formats.

-或--or- 小時元件和 s 中的 AM/PM 指示項不相符。The hour component and the AM/PM designator in s do not agree.

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

範例

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

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
                         "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
                         "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
                         "M/d/yyyy h:mm", "M/d/yyyy h:mm",
                         "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                         "MM/d/yyyy HH:mm:ss.ffffff" };
      string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
                              "5/1/2009 6:32:00", "05/01/2009 06:32",
                              "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00",
                              "08/28/2015 16:17:39.125", "08/28/2015 16:17:39.125000" };
      DateTime dateValue;

      foreach (string dateString in dateStrings)
      {
         try {
            dateValue = DateTime.ParseExact(dateString, formats,
                                            new CultureInfo("en-US"),
                                            DateTimeStyles.None);
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
         }
         catch (FormatException) {
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
         }
      }
   }
}
// The example displays the following output:
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
//       Unable to convert '08/28/2015 16:17:39.125' to a date.
//       Converted '08/28/2015 16:17:39.125000' to 8/28/2015 4:17:39 PM.
Imports System.Globalization

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

      Dim dateValue As DateTime
      
      For Each dateString As String In dateStrings
         Try
            dateValue = DateTime.ParseExact(dateString, formats, _
                                            New CultureInfo("en-US"), _
                                            DateTimeStyles.None)
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue)
         Catch e As FormatException
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString)
         End Try                                               
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
'       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
'       Unable to convert '08/28/2015 16:17:39.125' to a date.
'       Converted '08/28/2015 16:17:39.125000' to 8/28/2015 4:17:39 PM.

備註

DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)方法會剖析日期的字串表示,該日期符合指派給參數的任何一個模式 formatsThe DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) method parses the string representation of a date that matches any one of the patterns assigned to the formats parameter. 如果字串不 s 符合任何一個模式與參數所定義的任何變異 styles ,則方法會擲回 FormatExceptionIf the string s does not match any one of these patterns with any of the variations defined by the styles parameter, the method throws a FormatException. 除了比較 s 多個格式化模式,而不是單一格式模式,這個多載的行為與方法相同 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles)Aside from comparing s to multiple formatting patterns, rather than to a single formatting pattern, this overload behaves identically to the DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method.

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

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

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

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

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

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

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

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

給呼叫者的注意事項

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

另請參閱

適用於

產品 推出的版本