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)
ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)
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 系统上测试应用程序以确保针对元号更改的准备情况信息。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);
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.

返回

一个对象,它等效于 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.

注解

@No__t-0 方法分析日期的字符串表示形式,该日期必须采用 format 参数定义的格式。The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter. 它还要求日期和时间的字符串表示形式的 @no__t 0Date > 和 @no__t 1Time > 元素按 @no__t 指定的顺序出现,并且 @no__t 3 除了 @no__t 所允许的空格外,不具有空格。It 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 定义不包含时间元素的日期并且分析操作成功,则生成的 @no__t 1 值的时间为午夜(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 定义不包含日期元素的时间并且分析操作成功,则生成的 @no__t 1 值的日期为 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 不表示特定时区中的时间并且分析操作成功,则返回的 DateTime 值的 @no__t 属性将为 DateTimeKind.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" 自定义格式说明符),返回的 DateTime 值的 @no__t 3 属性为 DateTimeKind.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.

@No__t 的参数是包含单个标准格式说明符的字符串,或者是一个或多个定义格式为 @no__t 的所需格式的自定义格式说明符。The format parameter is a string that contains either a single standard format specifier, or one or more custom format specifiers that define the required 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")的自定义格式模式,请对 @no__t 1 参数和每个自定义格式说明符的最宽形式使用固定区域性。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".

@No__t-0 中使用的特定日期和时间符号和字符串(如一周中的几天的名称)是由 provider 参数定义的,如果 @no__t 为标准格式说明符字符串,则 s 的精确格式。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. @No__t 参数可以是以下任何参数:The provider parameter can be any of the following:

  • 一个 @no__t 0 对象,表示用于解释 @no__t 的区域性。A CultureInfo object that represents the culture used to interpret s. 由其 DateTimeFormat 属性返回的 @no__t 0 对象用于定义 s 中的符号和格式设置。The DateTimeFormatInfo object returned by its DateTimeFormat property defines the symbols and formatting in s.

  • 一个 @no__t 0 对象,该对象定义日期和时间数据的格式。A DateTimeFormatInfo object that defines the format of date and time data.

  • 自定义 @no__t 0 实现,其 @no__t 方法返回 CultureInfo 对象或提供格式设置信息的 @no__t 3 对象。A custom IFormatProvider implementation whose GetFormat method returns either the CultureInfo object or the DateTimeFormatInfo object that provides formatting information.

如果 provider @no__t 为-1,则使用与当前区域性对应的 CultureInfo 对象。If provider is null, the CultureInfo object that corresponds to the current culture is used.

调用方说明

.NET Framework 4.NET Framework 4 中,如果要分析的字符串包含一个小时部分和一个不在协议中的 AM/PM 指示符,ParseExact 方法将引发 FormatExceptionIn 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. 在 @no__t 0 及更早版本中,将忽略 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)

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

参数

format
ReadOnlySpan<Char>
provider
IFormatProvider

返回

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

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

参数

formats
String[]
provider
IFormatProvider

返回

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);
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 中的样式元素或从 sDateTime 值的转换。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.

返回

一个对象,它等效于 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. 请注意,当 styles 参数等于 DateTimeStyles.None 时无法成功分析字符串 "5/01/2009 8:30 AM",因为 format 不允许使用前导空格。Note 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. 此外,无法通过 format of "MM/dd/yyyyhh: MM" 成功分析字符串 "5/01/2009 09:00",因为日期字符串不在月份号之前带有前导零,如 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).

注解

@No__t-0 方法分析日期的字符串表示形式,该日期必须采用 format 参数定义的格式。The 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 中的日期和时间元素按 @no__t 指定的顺序出现。It also requires that the date and time elements in s appear in the order specified by format. 如果 s 与 @no__t 参数的模式不匹配,并且具有 style 参数定义的任何变体,则该方法将引发 @no__t。If 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) 方法会分析格式提供程序的 @no__t 对象所识别的任意一种格式的日期的字符串表示形式。In 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. @No__t-0 方法还允许 @no__t 中的日期和时间元素按任意顺序显示。The DateTime.Parse(String, IFormatProvider, DateTimeStyles) method also allows the date and time elements in s to appear in any order.

如果 @no__t 0 参数只包含时间而不包含日期,则使用当前日期,除非 @no__t 参数包括 @no__t 2 标志,在这种情况下,将使用默认日期(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. @No__t 的参数还决定了 @no__t 参数是否可以包含前导空白字符和尾随空格字符。The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters.

如果 s 不包含时区信息,则返回的 DateTime 对象的 @no__t 属性为 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is DateTimeKind.Unspecified. 此行为可以通过使用 DateTimeStyles.AssumeLocal 标志来更改,该标志返回 Kind 属性为 DateTimeKind.Local 的 @no__t 1 值,或者使用 DateTimeStyles.AssumeUniversalDateTimeStyles.AdjustToUniversal 标志,该标志返回 Kind 属性为 DateTimeKind.Utc 的值。This 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 包含时区信息,则时间将转换为本地时间(如有必要),并将返回的 DateTime 对象的 @no__t 属性设置为 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)转换为本地时间,并将 @no__t 属性设置为 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.

@No__t-0 参数定义 @no__t 参数的所需模式。The 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.

如果在自定义格式模式下不使用日期或时间分隔符,请对 @no__t 参数和每个自定义格式说明符的最宽形式使用固定区域性。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".

备注

您可以调用 @no__t 方法并指定多个允许的格式,而不是要求 s 符合一种格式,以便分析操作成功。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.

@No__t 的参数包含一个或多个 @no__t 1 枚举的成员,该枚举确定 format 未定义的空格是否可以出现在 @no__t 3 中并控制分析操作的确切行为的位置。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 枚举的每个成员如何影响 @no__t 方法的操作。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 @no__t 不包含 DateTimeStyles.AssumeLocal 标志,则方法会分析该字符串,调用 ToUniversalTime 将返回的第5个值转换为 UTC,并将 Kind 属性设置为 @no__t。If 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 标志,则方法会分析字符串,对返回的 @no__t 值不执行时区转换,并设置 @no__t 属性到 DateTimeKind.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 未定义的空白可出现在 @no__t 1 的开头。Specifies that white space not defined by format can appear at the beginning of s.
AllowTrailingWhite 指定 format 未定义的空白可出现在 s 的末尾。Specifies that white space not defined by format can appear at the end of s.
AllowWhiteSpaces 指定 s 可以包含 format 未定义的前导空格、内部空格和尾随空格。Specifies 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 标志,否则返回的 DateTime 值的 @no__t 属性将设置为 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 转换为本地时间,并将其 @no__t 2 属性设置为 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 @No__t 使用默认值分析参数。The s parameter is parsed using default values. 不允许使用 format 中提供的空格。No white space other than that present in format is allowed. 如果 s 缺少日期部分,则返回的 @no__t 值的日期设置为1/1/0001。If s lacks a date component, the date of the returned DateTime value is set to 1/1/0001. 如果 s 不包含时区信息,则返回的 DateTime 对象的 @no__t 属性将设置为 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is set to DateTimeKind.Unspecified. 如果 s 中存在时区信息,则时间将转换为本地时间,而返回的 DateTime 对象的 @no__t 属性将设置为 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 值日期和时间,并将其 @no__t 属性设置为 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 中使用的特定日期和时间符号和字符串(例如特定语言中星期几的名称)由 provider 参数定义,如果 @no__t 为标准格式说明符字符串,则 s 的精确格式。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. @No__t 参数可以是以下任何参数:The provider parameter can be any of the following:

  • 一个 @no__t 0 对象,表示用于解释 @no__t 的区域性。A CultureInfo object that represents the culture used to interpret s. 由其 DateTimeFormat 属性返回的 @no__t 0 对象用于定义 s 中的符号和格式设置。The DateTimeFormatInfo object returned by its DateTimeFormat property defines the symbols and formatting in s.

  • 一个 @no__t 0 对象,该对象定义日期和时间数据的格式。A DateTimeFormatInfo object that defines the format of date and time data.

  • 自定义 @no__t 0 实现,其 @no__t 方法返回 CultureInfo 对象或提供格式设置信息的 @no__t 3 对象。A custom IFormatProvider implementation whose GetFormat method returns either the CultureInfo object or the DateTimeFormatInfo object that provides formatting information.

如果 provider @no__t 为-1,则使用与当前区域性对应的 CultureInfo 对象。If provider is null, the CultureInfo object that corresponds to the current culture is used.

调用方说明

.NET Framework 4.NET Framework 4 中,如果要分析的字符串包含一个小时部分和一个不在协议中的 AM/PM 指示符,ParseExact 方法将引发 FormatExceptionIn 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. 在 @no__t 0 及更早版本中,将忽略 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);
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.

返回

一个对象,它等效于 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.

注解

@No__t-0 方法分析与分配给 formats 参数的模式之一匹配的日期的字符串表示形式。The 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 与多个格式设置模式(而不是单个格式设置模式)进行比较以外,此重载的行为与 @no__t 1 方法相同。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.

@No__t 的参数包含要分析的日期和时间。The s parameter contains the date and time to parse. 如果 @no__t 0 参数只包含时间而不包含日期,则使用当前日期,除非 @no__t 参数包括 @no__t 2 标志,在这种情况下,将使用默认日期(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. @No__t-0 参数还可确定 @no__t 参数是否可以包含前导、内部或尾随空格字符,而不能包含 formats 中的格式字符串之一允许的空白字符。The 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 不包含时区信息,则返回的 DateTime 对象的 @no__t 属性为 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is DateTimeKind.Unspecified. 此行为可以通过使用 DateTimeStyles.AssumeLocal 标志来更改,该标志返回 Kind 属性为 DateTimeKind.Local 的 @no__t 1 值,或者使用 DateTimeStyles.AssumeUniversalDateTimeStyles.AdjustToUniversal 标志,该标志返回 Kind 属性为 DateTimeKind.Utc 的值。This 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 包含时区信息,则时间将转换为本地时间(如有必要),并将返回的 DateTime 对象的 @no__t 属性设置为 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)转换为本地时间,并将 @no__t 属性设置为 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.

@No__t 的参数包含一系列模式,其中 @no__t 一个模式必须完全匹配(如果分析操作成功)。The formats parameter contains an array of patterns, one of which s must match exactly if the parse operation is to succeed. @No__t 参数中的模式包括自定义日期和时间格式字符串表中的一个或多个自定义格式说明符,或从标准日期和时间标识预定义模式的单个标准格式说明符。格式字符串表。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.

如果在自定义格式模式下不使用日期或时间分隔符,请对 @no__t 参数和每个自定义格式说明符的最宽形式使用固定区域性。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".

@No__t 的参数包含一个或多个 @no__t 1 枚举的成员,该枚举确定 format 未定义的空格是否可以出现在 @no__t 3 中并控制分析操作的确切行为的位置。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 枚举的每个成员如何影响 @no__t 方法的操作。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 @no__t 不包含 DateTimeStyles.AssumeLocal 标志,则方法会分析该字符串,调用 ToUniversalTime 将返回的第5个值转换为 UTC,并将 Kind 属性设置为 @no__t。If 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 标志,则方法会分析字符串,对返回的 @no__t 值不执行时区转换,并设置 @no__t 属性到 DateTimeKind.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 未定义的空白可出现在 @no__t 1 的开头。Specifies that white space not defined by format can appear at the beginning of s.
AllowTrailingWhite 指定 format 未定义的空白可出现在 s 的末尾。Specifies that white space not defined by format can appear at the end of s.
AllowWhiteSpaces 指定 s 可以包含 format 未定义的前导空格、内部空格和尾随空格。Specifies 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 标志,否则返回的 DateTime 值的 @no__t 属性将设置为 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 转换为本地时间,并将其 @no__t 2 属性设置为 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 @No__t 使用默认值分析参数。The s parameter is parsed using default values. 不允许使用 format 中提供的空格。No white space other than that present in format is allowed. 如果 s 缺少日期部分,则返回的 @no__t 值的日期设置为1/1/0001。If s lacks a date component, the date of the returned DateTime value is set to 1/1/0001. 如果 s 不包含时区信息,则返回的 DateTime 对象的 @no__t 属性将设置为 DateTimeKind.UnspecifiedIf s contains no time zone information, the Kind property of the returned DateTime object is set to DateTimeKind.Unspecified. 如果 s 中存在时区信息,则时间将转换为本地时间,而返回的 DateTime 对象的 @no__t 属性将设置为 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 中使用的特定日期和时间符号和字符串(例如特定语言中星期几的名称)由 provider 参数定义,如果 @no__t 为标准格式说明符字符串,则 s 的精确格式。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. @No__t 参数可以是以下任何参数:The provider parameter can be any of the following:

  • 一个 @no__t 0 对象,表示用于解释 @no__t 的区域性。A CultureInfo object that represents the culture used to interpret s. 由其 DateTimeFormat 属性返回的 @no__t 0 对象用于定义 s 中的符号和格式设置。The DateTimeFormatInfo object returned by its DateTimeFormat property defines the symbols and formatting in s.

  • 一个 @no__t 0 对象,该对象定义日期和时间数据的格式。A DateTimeFormatInfo object that defines the format of date and time data.

  • 自定义 @no__t 0 实现,其 @no__t 方法返回 CultureInfo 对象或提供格式设置信息的 @no__t 3 对象。A custom IFormatProvider implementation whose GetFormat method returns either the CultureInfo object or the DateTimeFormatInfo object that provides formatting information.

如果 provider @no__t 为-1,则使用与当前区域性对应的 CultureInfo 对象。If provider is null, the CultureInfo object that corresponds to the current culture is used.

调用方说明

.NET Framework 4.NET Framework 4 中,如果要分析的字符串包含一个小时部分和一个不在协议中的 AM/PM 指示符,ParseExact 方法将引发 FormatExceptionIn 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. 在 @no__t 0 及更早版本中,将忽略 AM/PM 指示符。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, the AM/PM designator is ignored.

另请参阅

适用于