DateTime.TryParseExact DateTime.TryParseExact DateTime.TryParseExact DateTime.TryParseExact Method

定义

将日期和时间的指定字符串表示形式转换为其等效的 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. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

重载

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

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 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. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 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. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

注解

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。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.

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)

public:
 static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles *  -> bool
Public Shared Function TryParseExact (s As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

参数

format
ReadOnlySpan<Char>

返回

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

public:
 static bool TryParseExact(ReadOnlySpan<char> s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (ReadOnlySpan<char> s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.DateTimeStyles *  -> bool
Public Shared Function TryParseExact (s As ReadOnlySpan(Of Char), formats As String(), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

参数

formats
String[]

返回

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 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. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(System::String ^ s, System::String ^ format, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : string * string * IFormatProvider * System.Globalization.DateTimeStyles *  -> bool
Public Shared Function TryParseExact (s As String, format As String, provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

参数

s
String String String String

包含要转换的日期和时间的字符串。A string containing a date and time to convert.

format
String String String String

所需的 s 格式。The required format of s.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s.

style
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

一个或多个枚举值的按位组合,指示 s 允许使用的格式。A bitwise combination of one or more enumeration values that indicate the permitted format of s.

result
DateTime DateTime DateTime DateTime

当此方法返回时,如果转换成功,则包含与 DateTime 中包含的日期和时间等效的 s 值;如果转换失败,则为 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 sformat 参数为 null,或者为空字符串,或者未包含对应于 format 中指定的模式的日期和时间,则转换失败。The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date and time that correspond to the pattern specified in format. 此参数未经初始化即被传递。This parameter is passed uninitialized.

返回

如果 true 成功转换,则为 s;否则为 falsetrue if s was converted successfully; otherwise, false.

异常

styles 不是有效的 DateTimeStyles 值。styles is not a valid DateTimeStyles value.

-or- styles 包含无效的 DateTimeStyles 值组合(例如,AssumeLocalAssumeUniversal)。styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

示例

下面的示例演示DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)方法。The following example demonstrates the DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 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 "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";
      if (DateTime.TryParseExact(dateString, "g", enUS, 
                                 DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

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

      // Allow a leading space in the date string.
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, 
                              DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         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"; 
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, 
                              DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      // Allow a leading space in the date string.
      if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, 
                              DateTimeStyles.AdjustToUniversal, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
           
      // Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z";
      if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                     DateTimeStyles.None, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

      if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, 
                                 DateTimeStyles.RoundtripKind, out dateValue))
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
                           dateValue.Kind);
      else
         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

Public 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"
      If Date.TryParseExact(dateString, "g", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "g", enUS, _
                            DateTimeStyles.AllowLeadingWhite, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      
      ' Use custom formats with M and MM.
      dateString = "5/01/2009 09:00"
      If Date.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If

      ' Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00" 
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      ' Allow a leading space in the date string.
      If Date.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                            DateTimeStyles.AdjustToUniversal, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
           
      ' Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z"
      If Date.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                                     DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
      
      If Date.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                            DateTimeStyles.RoundtripKind, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If
   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).

注解

方法分析日期的字符串表示形式, 该日期必须采用format参数定义的格式。 DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)The DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method parses the string representation of a date, which must be in the format defined by the format parameter. 它与DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles)方法类似, 不同TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)的是, 如果转换失败, 方法不会引发异常。It is similar to the DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method, except that the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method does not throw an exception if the conversion fails.

参数包含要分析的日期和时间, 其格式必须为参数所format定义的格式。 sThe s parameter contains the date and time to parse and must be in a format defined by the format parameter. 如果中s存在日期、时间和时区元素, 则它们也必须按format指定的顺序出现。If date, time, and time zone elements are present in s, they must also appear in the order specified 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.Date值具有日期, 或者DateTimeStyles.NoCurrentDateDefault它的日期DateTime.MinValue.Date为 (如果styles包含标志)。If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value by default has a date of DateTime.Now.Date, or it has a date of DateTime.MinValue.Date if styles includes the DateTimeStyles.NoCurrentDateDefault flag. 参数确定s参数是否可以包含前导空白字符和尾随空格字符。 styleThe style parameter determines whether the s parameter can contain leading, inner, or trailing white space characters.

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

参数包含对应于所需的s参数格式的模式。 formatThe format parameter contains a pattern that corresponds to the expected format of the s parameter. format参数中的模式包括自定义日期和时间格式字符串表中的一个或多个自定义格式说明符, 或从标准日期和时间格式字符串表。The pattern in the format 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".

备注

您可以s DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)调用方法并指定多个允许的格式, 而不是要求符合一种格式以便分析操作成功。Rather than requiring that s conform to a single format for the parse operation to succeed, you can call the DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method and specify multiple permitted formats. 这使得分析操作更有可能成功。This makes the parse operation more likely to succeed.

s使用的特定日期和时间符号和字符串 (如一周中的星期几的名称) 是provider由参数定义的, s如果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.

参数包含一个或多个DateTimeStyles枚举成员, 这些成员确定是否format可以在中s显示未定义的, 以及是否能够控制分析操作的确切行为。 stylesThe 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枚举的每个成员如何影响该TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)方法的操作。The following table describes how each member of the DateTimeStyles enumeration affects the operation of the TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) method.

DateTimeStyles 成员DateTimeStyles member 说明Description
AdjustToUniversal 分析s并根据需要将其转换为 UTC。Parses s and, if necessary, converts it to UTC. 如果s包括时区偏移量, 或者如果s不包含任何时区信息, 但styles DateTimeStyles.AssumeLocal包含标志, 则方法会分析该字符串, 调用ToUniversalTime将返回DateTime值转换为 UTC, 并将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的执行时区转换值, 并将Kind属性设置为。 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定义的空白可出现在的s开头。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 指定可能包含未定义的format前导空格、内部空格和尾随空格。 sSpecifies 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. 除非存在Kind DateTime标志, 否则返回值的属性将设置为DateTimeKind.LocalDateTimeStyles.AdjustToUniversalUnless 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. 除非存在DateTime Kind DateTimeKind.Local标志, 否则方法会将返回的值从 UTC 转换为本地时间, 并将其属性设置为。 DateTimeStyles.AdjustToUniversalUnless 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 使用默认值分析参数。sThe s parameter is parsed using default values. 不允许使用以外的format任何空白区域。No 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 对于包含时区信息的字符串, 尝试防止转换为DateTimeKind属性设置为DateTimeKind.Local的值。For strings that contain time zone information, tries to prevent the conversion to a DateTime value with its Kind property set to DateTimeKind.Local. 此标志主要用于防止 UTC 时间转换为本地时间。This flag primarily prevents the conversion of UTC times to local times.

调用方说明

在中TryParseExact false , 如果要分析的字符串包含不在协议中的小时组件和 AM/PM 指示符, 则方法将返回。 .NET Framework 4.NET Framework 4In the .NET Framework 4.NET Framework 4, the TryParseExact method returns false 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.

另请参阅

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 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. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParseExact(System::String ^ s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParseExact (string s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
static member TryParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles *  -> bool
Public Shared Function TryParseExact (s As String, formats As String(), provider As IFormatProvider, style As DateTimeStyles, ByRef result As DateTime) As Boolean

参数

s
String String String String

包含要转换的日期和时间的字符串。A string that contains a date and time to convert.

formats
String[]

s 的允许格式的数组。An array of allowable formats of s.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

一个对象,提供有关 s 的区域性特定格式信息。An object that supplies culture-specific format information about s.

style
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

枚举值的一个按位组合,指示 s 所允许的格式。A bitwise combination of enumeration values that indicates the permitted format of s. 要指定的一个典型值为 NoneA typical value to specify is None.

result
DateTime DateTime DateTime DateTime

当此方法返回时,如果转换成功,则包含与 DateTime 中包含的日期和时间等效的 s 值;如果转换失败,则为 MinValueWhen this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. 如果 sformatsnullsformats 的某个元素为空字符串, 或者 s 的格式与 formats 中的格式模式所指定的格式都不完全匹配,则转换失败。The conversion fails if s or formats is null, s or an element of formats is an empty string, or the format of s is not exactly as specified by at least one of the format patterns in formats. 此参数未经初始化即被传递。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 s;否则为 falsetrue if the s parameter was converted successfully; otherwise, false.

异常

styles 不是有效的 DateTimeStyles 值。styles is not a valid DateTimeStyles value.

-or- styles 包含无效的 DateTimeStyles 值组合(例如,AssumeLocalAssumeUniversal)。styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

示例

下面的示例使用DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)方法来确保可以成功分析多种可能格式的字符串。The following example uses the DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) 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"};
      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"}; 
      DateTime dateValue;
      
      foreach (string dateString in dateStrings)
      {
         if (DateTime.TryParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
                                    DateTimeStyles.None, 
                                    out dateValue))
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
         else
            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.
Imports System.Globalization

Public 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"}
      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"} 

      Dim dateValue As DateTime
      
      For Each dateString As String In dateStrings
         If Date.TryParseExact(dateString, formats, _
                               New CultureInfo("en-US"), _
                               DateTimeStyles.None, _
                               dateValue) Then
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue)
         Else
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString)
         End If                                               
      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.

注解

方法分析与分配formats给参数的模式之一匹配的日期的字符串表示形式。 DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)The DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method parses the string representation of a date that matches any one of the patterns assigned to the formats parameter. 它与DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)方法类似, TryParseExact不同的是, 如果转换失败, 方法不会引发异常。It is like the DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) method, except the TryParseExact method does not throw an exception if the conversion fails.

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

参数包含模式的数组, 其中一个s模式必须完全匹配 (如果分析操作成功)。 formatsThe 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 consist 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".

s使用的特定日期和时间符号和字符串 (如一周中的星期几的名称) 是provider由参数定义的, s如果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.

参数包含一个或多个DateTimeStyles枚举成员, 这些成员确定是否format可以在中s显示未定义的, 以及是否能够控制分析操作的确切行为。 stylesThe 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枚举的每个成员如何影响该TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)方法的操作。The following table describes how each member of the DateTimeStyles enumeration affects the operation of the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method.

DateTimeStyles 成员DateTimeStyles member 说明Description
AdjustToUniversal 分析s并根据需要将其转换为 UTC。Parses s and, if necessary, converts it to UTC. 如果s包括时区偏移量, 或者如果s不包含任何时区信息, 但styles DateTimeStyles.AssumeLocal包含标志, 则方法会分析该字符串, 调用ToUniversalTime将返回DateTime值转换为 UTC, 并将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的执行时区转换值, 并将Kind属性设置为。 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定义的空白可出现在的s开头。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 指定可能包含未定义的format前导空格、内部空格和尾随空格。 sSpecifies 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. 除非存在Kind DateTime标志, 否则返回值的属性将设置为DateTimeKind.LocalDateTimeStyles.AdjustToUniversalUnless 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. 除非存在DateTime Kind DateTimeKind.Local标志, 否则方法会将返回的值从 UTC 转换为本地时间, 并将其属性设置为。 DateTimeStyles.AdjustToUniversalUnless 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 使用默认值分析参数。sThe s parameter is parsed using default values. 不允许使用以外的format任何空白区域。No 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 对于包含时区信息的字符串, 尝试防止转换为DateTimeKind属性设置为DateTimeKind.Local的值。For strings that contain time zone information, tries to prevent the conversion to a DateTime value with its Kind property set to DateTimeKind.Local. 此标志主要用于防止 UTC 时间转换为本地时间。This flag primarily prevents the conversion of UTC times to local times.

调用方说明

在中TryParseExact false , 如果要分析的字符串包含不在协议中的小时组件和 AM/PM 指示符, 则方法将返回。 .NET Framework 4.NET Framework 4In the .NET Framework 4.NET Framework 4, the TryParseExact method returns false 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.

另请参阅

适用于