DateTime.ParseExact 方法   
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。
重载
| ParseExact(String, String, IFormatProvider) | 使用指定的格式和区域性特定格式信息,将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配。 | 
| ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) | 使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定范围表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。 | 
| ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) | 使用指定的格式数组、区域性特定的格式信息和样式将日期和时间的指定范围表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。 | 
| ParseExact(String, String, IFormatProvider, DateTimeStyles) | 使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。 | 
| ParseExact(String, String[], IFormatProvider, DateTimeStyles) | 使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。 | 
注解
重要
日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。 例如,2019 年 5 月 1 日在 JapaneseCalendar 和 JapaneseLunisolarCalendar 中标志着令和年号的开始。 这种年号的变化会影响使用这些日历的所有应用程序。 有关详细信息以及如何确定应用程序是否受影响,请参阅在 .net 中的日式日历中处理新时代。 若要了解如何在 Windows 系统上测试应用程序以确保其应用程序更改的就绪性,请参阅准备应用程序以进行日本时代更改。 对于 .NET 中支持多个纪元的日历的功能,以及在处理支持多个纪元的日历时的最佳做法,请参阅使用 纪元。
ParseExact(String, String, IFormatProvider)
使用指定的格式和区域性特定格式信息,将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配。
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 -> DateTimePublic Shared Function ParseExact (s As String, format As String, provider As IFormatProvider) As DateTime参数
- s
- String
包含要转换的日期和时间的字符串。
- format
- String
用于定义所需的 s 格式的格式说明符。 有关详细信息,请参阅“备注”部分。
- provider
- IFormatProvider
一个对象,提供有关 s 的区域性特定格式信息。
返回
一个对象,它等效于 s 中包含的日期和时间,由 format 和 provider 指定。
例外
s 或 format 为 null。
示例
下面的示例演示 ParseExact 方法。
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)方法分析日期的字符串表示形式,该表示形式必须采用 参数定义 format 的格式。 它还要求日期和时间的字符串表示形式中的 和 元素按 指定的顺序显示,并且除了 允许的空格外,没有 <Date> <Time> format s 空格 format 。 如果 定义没有时间元素的日期,并且分析操作成功,则生成的值具有午夜 format DateTime (00:00:00) 。 如果 format 定义一个没有日期元素的时间,并且分析操作成功,则结果 DateTime 值的日期为 DateTime.Now.Date 。
如果 s 不表示特定时区中的时间,并且分析操作成功,则返回 Kind 值的 DateTime 属性为 DateTimeKind.Unspecified 。 如果 确实表示特定时区中的时间并允许显示时区信息 (例如,如果 等于"o"、"r"或"u"标准格式说明符,或者如果它包含 s format format "z"、"zz"或"zzz"自定义格式说明符) ,则返回值的 Kind DateTime 属性为 DateTimeKind.Local 。
参数是包含单个标准格式说明符或一个或多个自定义格式说明符(用于定义 所需格式 format )的字符串 s 。 有关有效格式设置代码的详细信息,请参阅 标准日期和时间格式字符串 或 自定义日期和时间格式字符串。
备注
如果 是不包含日期或时间分隔符 (如 format "yyyyMMddHHmm") 的自定义格式模式,请对 参数使用固定区域性,并使用每个自定义格式说明符的最宽格式。 provider 例如,如果要在格式模式中指定小时,请指定较宽的窗体"HH",而不是较窄的窗体"H"。
特定的日期和时间符号和字符串 (如 中使用的特定语言) 中的星期几的名称由 参数定义,正如 如果 是标准格式说明符字符串的精确格式一样。 s provider s format provider参数可以是以下任一项:
- 一 CultureInfo 个 对象,该对象表示用于解释 的区域性 - s。 DateTimeFormatInfo其 属性返回 DateTimeFormat 的对象定义 中的符号和格式- s设置。
- 一 DateTimeFormatInfo 个 定义日期和时间数据格式的 对象。 
- 一个 IFormatProvider 自定义实现 GetFormat ,其 方法返回 CultureInfo 提供 DateTimeFormatInfo 格式设置信息的 对象或 对象。 
如果 provider null 为 , CultureInfo 则使用与当前区域性对应的 对象。
调用方说明
在 .NET Framework 4 中,如果要分析的字符串包含一个小时部分和一个不一致 AM/PM 表示符,则 方法 ParseExact FormatException 将引发 。 在 .NET Framework 3.5 及更早版本中,将忽略 AM/PM 设计器。
另请参阅
- TryParseExact
- CultureInfo
- DateTimeFormatInfo
- 在 .NET Framework 中分析日期和时间字符串
- 标准日期和时间格式字符串
- 自定义日期和时间格式字符串
适用于
ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)
使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定范围表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。
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 -> DateTimePublic 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>
一个范围,包含表示要转换的日期和时间的字符。
- format
- ReadOnlySpan<Char>
一个范围,包含表示用于定义所需的 s 格式的格式说明符的字符。
- provider
- IFormatProvider
一个对象,提供有关 s 的区域性特定格式设置信息。
- style
- DateTimeStyles
枚举值的按位组合,提供有关以下内容的附加信息:s、可能出现在 s 中的样式元素或从 s 到 DateTime 值的转换。 要指定的一个典型值为 None。
返回
一个对象,它等效于 s 中包含的日期和时间,由 format、provider 和 style 指定。
适用于
ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)
使用指定的格式数组、区域性特定的格式信息和样式将日期和时间的指定范围表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。
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 -> DateTimePublic 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>
一个范围,包含表示要转换的日期和时间的字符。
- formats
- String[]
s 的允许格式的数组。
- provider
- IFormatProvider
一个对象,提供有关 s 的区域性特定格式信息。
- style
- DateTimeStyles
枚举值的一个按位组合,指示 s 所允许的格式。 要指定的一个典型值为 None。
返回
一个对象,它等效于 s 中包含的日期和时间,由 formats、provider 和 style 指定。
适用于
ParseExact(String, String, IFormatProvider, DateTimeStyles)
使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。
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 -> DateTimePublic Shared Function ParseExact (s As String, format As String, provider As IFormatProvider, style As DateTimeStyles) As DateTime参数
- s
- String
包含要转换的日期和时间的字符串。
- format
- String
用于定义所需的 s 格式的格式说明符。 有关详细信息,请参阅“备注”部分。
- provider
- IFormatProvider
一个对象,提供有关 s 的区域性特定格式设置信息。
- style
- DateTimeStyles
枚举值的按位组合,提供有关以下内容的附加信息:s、可能出现在 s 中的样式元素或从 s 到 DateTime 值的转换。 要指定的一个典型值为 None。
返回
一个对象,它等效于 s 中包含的日期和时间,由 format、provider 和 style 指定。
例外
s 或 format 为 null。
style 包含无效的 DateTimeStyles 值组合。 例如,AssumeLocal 和 AssumeUniversal。
示例
下面的示例演示 ParseExact(String, String, IFormatProvider) 方法。 请注意,当 参数相等时,无法成功分析字符串"5/01/2009 8:30 AM",因为 不允许前导 styles DateTimeStyles.None 空格 format 。 此外,无法使用 format "MM/dd/yyyyh:mm"成功分析字符串"5/01/2009 09:00",因为日期字符串不按要求先于带前导零的月份号。 format
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)方法分析日期的字符串表示形式,该日期必须采用 参数定义的 format 格式。 它还要求 中的日期和时间元素按 s 指定的顺序显示 format 。 如果 与 参数的模式不匹配,与 参数定义的任何变体不匹配, s format 则 style 方法将引发 FormatException 。 相反, 方法分析日期的字符串表示形式,采用格式提供程序的 对象识别的任何一 DateTime.Parse(String, IFormatProvider, DateTimeStyles) DateTimeFormatInfo 种格式。 DateTime.Parse(String, IFormatProvider, DateTimeStyles)方法还允许 中的日期和时间元素 s 按任何顺序显示。
如果参数仅包含时间且不包含日期,则使用当前日期,除非参数包含 标志,在这种情况下,使用默认 () s style DateTimeStyles.NoCurrentDateDefault DateTime.Date.MinValue 日期。 如果 s 参数仅包含日期且不包含时间,则 (00:00:00) 午夜。 style参数还确定参数 s 是否可以包含前导、内部或尾随空格字符。
如果 s 不包含时区信息, Kind 则返回对象的 DateTime 属性为 DateTimeKind.Unspecified 。 可以使用 标志更改此行为,该标志返回属性为 的值,或者使用 和 标志(返回其 属性 DateTimeStyles.AssumeLocal DateTime 为 Kind DateTimeKind.Local DateTimeStyles.AssumeUniversal DateTimeStyles.AdjustToUniversal DateTime Kind 的值 DateTimeKind.Utc )。 如果 s 包含时区信息,则时间将转换为本地时间(如有必要)并且返回对象的 Kind DateTime 属性设置为 DateTimeKind.Local 。 可以通过使用 标志来更改此行为,以不将 协调世界时 (UTC) 转换为本地时间并将 DateTimeStyles.RoundtripKind Kind 属性设置为 DateTimeKind.Utc 。
format参数定义参数的必需 s 模式。 它可以由"自定义日期和时间格式字符串"表中的一个或多个自定义格式说明符或单个标准格式说明符(用于标识标准日期和时间格式字符串表中的预定义模式)组成。
如果不在自定义格式模式中使用日期或时间分隔符,请对 参数使用固定区域性,并使用每个自定义格式说明符 provider 的最宽格式。 例如,如果要在模式中指定小时,请指定较宽的窗体"HH",而不是较窄的窗体"H"。
备注
可以调用 方法并指定多个允许的格式,而不是要求符合单个格式的 分析操作 s DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 成功。 这使得分析操作更有可能成功。
参数包括 枚举的一个或多个成员,这些成员确定 未定义的空格是否可以出现在 中以及在何处显示,以及控制分析操作 styles DateTimeStyles format s 的确切行为。 下表描述了 枚举的每个 DateTimeStyles 成员如何影响 方法 ParseExact(String, String, IFormatProvider, DateTimeStyles) 的操作。
| DateTimeStyles 成员 | 说明 | 
|---|---|
| AdjustToUniversal | 分析 s,并在必要时将其转换为 UTC。 如果 包括时区偏移量,或者 如果 不包含时区信息但包含 标志,则 方法将分析字符串,调用 将返回的值转换为ssUTC,并将stylesDateTimeStyles.AssumeLocal ToUniversalTime DateTime Kind 属性设置为 DateTimeKind.Utc 。 如果 指示它表示 UTC,或者 如果 不包含时区信息,但包含 标志,则 方法将分析字符串,对返回的值不执行时区转换,将ssstylesDateTimeStyles.AssumeUniversal DateTime Kind 属性设置为 DateTimeKind.Utc 。 在所有其他情况下,标志不起作用。 | 
| AllowInnerWhite | 指定未定义的空白可在任何单独的日期 format或时间元素之间显示。 | 
| AllowLeadingWhite | 指定 未定义的空白 format可以出现在 的开头s。 | 
| AllowTrailingWhite | 指定 未定义的空白 format可以出现在 的末尾s。 | 
| AllowWhiteSpaces | 指定 可能包含未定义的前导空格、内部空格 s和尾随空格format。 | 
| AssumeLocal | 指定如果 s缺少任何时区信息,则假定它表示本地时间。 除非标志 DateTimeStyles.AdjustToUniversal 存在,否则返回值的 Kind DateTime 属性设置为 DateTimeKind.Local 。 | 
| AssumeUniversal | 指定如果 s缺少任何时区信息,则假定它表示 UTC。 除非标志存在,否则 方法会将返回的值从 UTC 转换为 DateTimeStyles.AdjustToUniversal DateTime 本地时间,并将其 Kind 属性设置为 DateTimeKind.Local 。 | 
| NoCurrentDateDefault | 如果 s包含不带日期信息的时间,则返回值的日期将设置为DateTime.MinValue.Date。 | 
| None | s使用默认值分析 参数。 不允许使用除 中的 空白format外的其他空格。 如果s缺少日期组件,则返回值的日期设置为 DateTime 1/1/0001。 如果s不包含时区信息, Kind 则返回对象的 DateTime 属性设置为 DateTimeKind.Unspecified 。 如果 中存在时区信息,s则时间将转换为本地时间,并且返回对象的 Kind DateTime 属性设置为 DateTimeKind.Local 。 | 
| RoundtripKind | 对于包含时区信息的字符串,尝试阻止转换为值日期和时间,其 DateTime Kind 属性设置为 DateTimeKind.Local 。 此标志主要阻止 UTC 时间转换为本地时间。 | 
参数定义特定的日期和时间符号和字符串 (如 中使用的特定语言) 中的星期几的名称,正如 如果 是标准格式说明符字符串的精确格式一样。 s provider s format provider参数可以是以下任一项:
- 一 CultureInfo 个 对象,该对象表示用于解释 的区域性 - s。 DateTimeFormatInfo其 属性返回 DateTimeFormat 的对象定义 中的符号和格式- s设置。
- 一 DateTimeFormatInfo 个 定义日期和时间数据格式的 对象。 
- 一个 IFormatProvider 自定义实现 GetFormat ,其 方法返回 CultureInfo 提供 DateTimeFormatInfo 格式设置信息的 对象或 对象。 
如果 provider null 为 , CultureInfo 则使用与当前区域性对应的 对象。
调用方说明
在 .NET Framework 4 中,如果要分析的字符串包含一个小时部分和一个不一致 AM/PM 表示符,则 方法 ParseExact FormatException 将引发 。 在 .NET Framework 3.5 及更早版本中,将忽略 AM/PM 设计器。
另请参阅
- TryParseExact
- CultureInfo
- DateTimeFormatInfo
- 在 .NET Framework 中分析日期和时间字符串
- 标准日期和时间格式字符串
- 自定义日期和时间格式字符串
适用于
ParseExact(String, String[], IFormatProvider, DateTimeStyles)
使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTime。 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。
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 -> DateTimePublic Shared Function ParseExact (s As String, formats As String(), provider As IFormatProvider, style As DateTimeStyles) As DateTime参数
- s
- String
包含要转换的日期和时间的字符串。
- formats
- String[]
s 的允许格式的数组。 有关详细信息,请参阅“备注”部分。
- provider
- IFormatProvider
一个对象,提供有关 s 的区域性特定格式信息。
- style
- DateTimeStyles
枚举值的一个按位组合,指示 s 所允许的格式。 要指定的一个典型值为 None。
返回
一个对象,它等效于 s 中包含的日期和时间,由 formats、provider 和 style 指定。
例外
s 或 formats 为 null。
s 是一个空字符串。
- 或 -
formats 的一个元素为空字符串。
- 或 -
s 不包含与 formats 中任意元素相对应的日期和时间。
- 或 -
s 中的小时组件和 AM/PM 指示符不一致。
style 包含无效的 DateTimeStyles 值组合。 例如,AssumeLocal 和 AssumeUniversal。
示例
下面的示例使用 DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 方法来确保可以成功分析多种可能格式的字符串。
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)方法分析日期的字符串表示形式,该日期与分配给 参数的任何一种 formats 模式匹配。 如果字符串与 参数定义的任何变体不匹配其中任何一种模式,则 s styles 方法将引发 FormatException 。 除了比较多个格式设置模式,而不是与单个格式设置模式相比,此重载的行为与 方法 s DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) 相同。
s参数包含要分析的日期和时间。 如果参数仅包含时间且不包含日期,则使用当前日期,除非参数包含 标志,在这种情况下,使用默认 () s style DateTimeStyles.NoCurrentDateDefault DateTime.Date.MinValue 日期。 如果 s 参数仅包含日期且不包含时间,则 (00:00:00) 午夜。 参数还确定 参数是否可以包含前导、内部或尾随空格字符,而不是 中的一个格式字符串 style s 所允许的空格 formats 字符。
如果 s 不包含时区信息, Kind 则返回对象的 DateTime 属性为 DateTimeKind.Unspecified 。 可以使用 标志更改此行为,该标志返回属性为 的值,或者使用 和 标志(返回其 属性 DateTimeStyles.AssumeLocal DateTime 为 Kind DateTimeKind.Local DateTimeStyles.AssumeUniversal DateTimeStyles.AdjustToUniversal DateTime Kind 的值 DateTimeKind.Utc )。 如果 s 包含时区信息,则时间将转换为本地时间(如有必要)并且返回对象的 Kind DateTime 属性设置为 DateTimeKind.Local 。 可以通过使用 标志来更改此行为,协调世界时 (UTC) 本地时间并将 DateTimeStyles.RoundtripKind Kind 属性设置为 DateTimeKind.Utc 。
参数包含模式数组,如果分析操作要成功,其中一个 formats s 模式必须完全匹配。 参数中的模式由自定义日期和时间格式字符串表中的一个或多个自定义格式说明符或单个标准格式说明符(用于标识标准日期和时间格式字符串表中的预定义模式)组成。 formats  
如果不在自定义格式模式中使用日期或时间分隔符,请对 参数使用固定区域性,并使用每个自定义格式说明符 provider 的最宽格式。 例如,如果要在模式中指定小时,请指定较宽的窗体"HH",而不是较窄的窗体"H"。
参数包括 枚举的一个或多个成员,这些成员确定 未定义的空格是否可以出现在 中以及在何处显示,以及控制分析操作 styles DateTimeStyles format s 的确切行为。 下表描述了 枚举的每个 DateTimeStyles 成员如何影响 方法 ParseExact(String, String, IFormatProvider, DateTimeStyles) 的操作。
| DateTimeStyles 成员 | 说明 | 
|---|---|
| AdjustToUniversal | 分析 s,并在必要时将其转换为 UTC。 如果 包括时区偏移量,或者 如果 不包含时区信息但包含 标志,则 方法将分析字符串,调用 将返回的值转换为ssUTC,并将stylesDateTimeStyles.AssumeLocal ToUniversalTime DateTime Kind 属性设置为 DateTimeKind.Utc 。 如果 指示它表示 UTC,或者 如果 不包含时区信息,但包含 标志,则 方法将分析字符串,对返回的值不执行时区转换,将ssstylesDateTimeStyles.AssumeUniversal DateTime Kind 属性设置为 DateTimeKind.Utc 。 在所有其他情况下,标志不起作用。 | 
| AllowInnerWhite | 指定未定义的空白可在任何单独的日期 format或时间元素之间显示。 | 
| AllowLeadingWhite | 指定 未定义的空白 format可以出现在 的开头s。 | 
| AllowTrailingWhite | 指定 未定义的空白 format可以出现在 的末尾s。 | 
| AllowWhiteSpaces | 指定 可能包含未定义的前导空格、内部空格 s和尾随空格format。 | 
| AssumeLocal | 指定如果 s缺少任何时区信息,则假定它表示本地时间。 除非标志 DateTimeStyles.AdjustToUniversal 存在,否则返回值的 Kind DateTime 属性设置为 DateTimeKind.Local 。 | 
| AssumeUniversal | 指定如果 s缺少任何时区信息,则假定它表示 UTC。 除非标志存在,否则 方法会将返回的值从 UTC 转换为 DateTimeStyles.AdjustToUniversal DateTime 本地时间,并将其 Kind 属性设置为 DateTimeKind.Local 。 | 
| NoCurrentDateDefault | 如果 s包含时间而不包含日期信息,则返回值的日期设置为DateTime.MinValue.Date。 | 
| None | s使用默认值分析参数。 不允许使用以外的任何空白区域format。 如果s缺少日期部分,则返回值的日期 DateTime 设置为1/1/0001。 如果s不包含时区信息,则 Kind 返回的对象的属性 DateTime 设置为 DateTimeKind.Unspecified 。 如果中存在时区信息,则s该时间将转换为本地时间,而 Kind 返回对象的属性将 DateTime 设置为 DateTimeKind.Local 。 | 
| RoundtripKind | 对于包含时区信息的字符串,尝试防止转换为其属性设置为的日期和时间 Kind DateTimeKind.Local 。 此标志主要用于防止 UTC 时间转换为本地时间。 | 
特定的日期和时间符号和字符串 (如中所用的特定语言) 的星期名称 s ,则该参数是由参数定义的 provider , s 如果 format 是标准格式说明符字符串,则是的精确格式。 provider参数可以是以下任一项:
- 一个 CultureInfo 对象,表示用于解释的区域性 - s。 DateTimeFormatInfo其属性返回的对象 DateTimeFormat 定义中的符号和格式设置- s。
- 一个 DateTimeFormatInfo 对象,该对象定义日期和时间数据的格式。 
- 一个自定义 IFormatProvider 实现,其 GetFormat 方法返回 CultureInfo DateTimeFormatInfo 提供格式设置信息的对象或对象。 
如果 provider 为 null ,则 CultureInfo 使用对应于当前区域性的对象。
调用方说明
在 .NET Framework 4 中, ParseExact FormatException 如果要分析的字符串包含一个小时部分和一个不在协议中的 AM/PM 指示符,则方法将引发。 在 .NET Framework 3.5 及更早版本中,将忽略 AM/PM 指示符。
另请参阅
- TryParseExact
- CultureInfo
- DateTimeFormatInfo
- 在 .NET Framework 中分析日期和时间字符串
- 标准日期和时间格式字符串
- 自定义日期和时间格式字符串