DateTime.TryParse DateTime.TryParse DateTime.TryParse DateTime.TryParse Method

定义

将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

重载

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)
TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime)

将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的区域性特定格式信息和格式设置样式,将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime)

注解

重要

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

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

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

参数

返回

TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime)

将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParse (string s, out DateTime result);
static member TryParse : string * DateTime -> bool
Public Shared Function TryParse (s As String, ByRef result As DateTime) As Boolean

参数

s
String String String String

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

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. 如果 s 参数为 null,是空字符串 ("") 或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. 此参数未经初始化即被传递。This parameter is passed uninitialized.

返回

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

示例

下面的示例将一些日期和时间字符串传递到 DateTime.TryParse(String, DateTime) 方法。The following example passes a number of date and time strings to the DateTime.TryParse(String, DateTime) method.

using namespace System;
using namespace System::Globalization;

void main()
{
   array<String^>^ dateStrings = { "05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8", 
                                   "2009-05-01T14:57:32.8375298-04:00", 
                                    "5/01/2008 14:57:32.80 -07:00", 
                                    "1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM", 
                                    "Fri, 15 May 2009 20:10:57 GMT" };
   DateTime dateValue;

   Console::WriteLine("Attempting to parse strings using {0} culture.", 
                     CultureInfo::CurrentCulture->Name);
   for each (String^ dateString in dateStrings)
   {
      if (DateTime::TryParse(dateString, dateValue)) 
         Console::WriteLine("  Converted '{0}' to {1} ({2}).", dateString, 
                           dateValue, dateValue.Kind);
      else
         Console::WriteLine("  Unable to parse '{0}'.", dateString);
   }
}
// The example displays the following output: 
//    Attempting to parse strings using en-US culture. 
//       Converted '05/01/2009 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified). 
//       Converted '2009-05-01 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified). 
//       Converted '2009-05-01T14:57:32.8375298-04:00' to 5/1/2009 11:57:32 AM (Local). 
//       Converted '5/01/2008 14:57:32.80 -07:00' to 5/1/2008 2:57:32 PM (Local). 
//       Converted '1 May 2008 2:57:32.8 PM' to 5/1/2008 2:57:32 PM (Unspecified). 
//       Unable to parse '16-05-2009 1:00:32 PM'. 
//       Converted 'Fri, 15 May 2009 20:10:57 GMT' to 5/15/2009 1:10:57 PM (Local).
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8",
                              "2009-05-01T14:57:32.8375298-04:00", "5/01/2008",
                              "5/01/2008 14:57:32.80 -07:00", 
                              "1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM", 
                              "Fri, 15 May 2009 20:10:57 GMT" };
      DateTime dateValue;
      
      Console.WriteLine("Attempting to parse strings using {0} culture.", 
                        CultureInfo.CurrentCulture.Name);
      foreach (string dateString in dateStrings)
      {
         if (DateTime.TryParse(dateString, out dateValue)) 
            Console.WriteLine("  Converted '{0}' to {1} ({2}).", dateString, 
                              dateValue, dateValue.Kind);
         else
            Console.WriteLine("  Unable to parse '{0}'.", dateString);
      }
   }
}
// The example displays output like the following:
//    Attempting to parse strings using en-US culture.
//      Converted '05/01/2009 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified).
//      Converted '2009-05-01 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified).
//      Converted '2009-05-01T14:57:32.8375298-04:00' to 5/1/2009 11:57:32 AM (Local).
//
//      Converted '5/01/2008' to 5/1/2008 12:00:00 AM (Unspecified).
//      Converted '5/01/2008 14:57:32.80 -07:00' to 5/1/2008 2:57:32 PM (Local).
//      Converted '1 May 2008 2:57:32.8 PM' to 5/1/2008 2:57:32 PM (Unspecified).
//      Unable to parse '16-05-2009 1:00:32 PM'.
//      Converted 'Fri, 15 May 2009 20:10:57 GMT' to 5/15/2009 1:10:57 PM (Local).
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim dateStrings() As String = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8",
                                     "2009-05-01T14:57:32.8375298-04:00", "5/01/2008",
                                     "5/01/2008 14:57:32.80 -07:00",
                                     "1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM",
                                     "Fri, 15 May 2009 20:10:57 GMT"}
      Dim dateValue As Date
      
      Console.WriteLine("Attempting to parse strings using {0} culture.", _
                        CultureInfo.CurrentCulture.Name)
      For Each dateString As String In dateStrings
         If Date.TryParse(dateString, dateValue) Then
            Console.WriteLine("  Converted '{0}' to {1} ({2}).", dateString, _
                              dateValue, dateValue.Kind)
         Else
            Console.WriteLine("  Unable to parse '{0}'.", dateString)
         End If
      Next
   End Sub
End Module
' The example displays output like the following:
'    Attempting to parse strings using en-US culture.
'      Converted '05/01/2009 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified).
'      Converted '2009-05-01 14:57:32.8' to 5/1/2009 2:57:32 PM (Unspecified).
'      Converted '2009-05-01T14:57:32.8375298-04:00' to 5/1/2009 11:57:32 AM (Local).
'
'      Converted '5/01/2008' to 5/1/2008 12:00:00 AM (Unspecified).
'      Converted '5/01/2008 14:57:32.80 -07:00' to 5/1/2008 2:57:32 PM (Local).
'      Converted '1 May 2008 2:57:32.8 PM' to 5/1/2008 2:57:32 PM (Unspecified).
'      Unable to parse '16-05-2009 1:00:32 PM'.
'      Converted 'Fri, 15 May 2009 20:10:57 GMT' to 5/15/2009 1:10:57 PM (Local).

注解

@No__t-0 方法类似于 DateTime.Parse(String) 方法,但如果转换失败,TryParse(String, DateTime) 方法不会引发异常。The DateTime.TryParse(String, DateTime) method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails.

字符串 s 使用当前 DateTimeFormatInfo 对象中的格式设置信息进行分析,该对象由当前线程区域性隐式提供。The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.

此方法尝试忽略无法识别的数据(如果可能),并用当前日期填充缺少的月、日和年信息。This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. 如果 s 只包含日期而不包含时间,则该方法假定时间为12:00 午夜。If s contains only a date and no time, this method assumes the time is 12:00 midnight. 如果 s 包含带有两位数年份的日期部分,则将根据 Calendar.TwoDigitYearMax 属性的值将其转换为当前区域性当前日历中的年份。If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. @No__t-0 中的任何前导、内部或尾随空格字符都将被忽略。Any leading, inner, or trailing white space character in s is ignored. 日期和时间可以用一对前导和尾随数字符号字符("#"、U + 0023)括起来,并且可以使用一个或多个 NULL 字符(U + 0000)进行 trailed。The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).

由于 @no__t 0 方法尝试使用当前区域性的格式设置规则来分析日期和时间的字符串表示形式,因此尝试跨不同区域性分析特定字符串可能会失败或返回不同的结果。Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. 如果将在不同的区域设置中分析特定的日期和时间格式,请使用 DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 方法或 @no__t 方法的重载之一,并提供格式说明符。If a specific date and time format will be parsed across different locales, use the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method or one of the overloads of the TryParseExact method and provide a format specifier.

如果 @no__t 为当前日历中闰年的闰年的字符串表示形式,则该方法将成功分析 @no__t。If s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. 如果 @no__t 为当前区域性当前日历中非闰年的闰日的字符串表示形式,则分析操作将失败,并且该方法将返回 falseIf s is the string representation of a leap day in a non-leap year in the current culture's current calendar, the parse operation fails and the method returns false.

如果 s 不包含时区信息,result 将包含一个 @no__t 2 值,如果该方法返回,则该属性的 @no__t 3 属性为 @no__t。If s contains no time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Unspecified when the method returns. 如果要分析的字符串包含时区信息,result 包含 @no__t 1 值,如果方法返回,则其 @no__t 2 属性将 @no__t 为-3。If the string to be parsed contains time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Local when the method returns.

调用方说明

格式设置受当前 DateTimeFormatInfo 对象的属性影响,默认情况下,它派生自控制面板中的 "区域和语言选项" 项。Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. 如果当前 @no__t 和 @no__t 属性设置为相同的值,TryParse 方法可能会意外失败并返回 FalseThe TryParse method can unexpectedly fail and return False if the current DateSeparator and TimeSeparator properties are set to the same value.

另请参阅

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的区域性特定格式信息和格式设置样式,将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

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

参数

s
String String String String

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

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

styles
DateTimeStyles DateTimeStyles DateTimeStyles DateTimeStyles

枚举值的按位组合,该组合定义如何根据当前时区或当前日期解释已分析日期。A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. 要指定的一个典型值为 NoneA typical value to specify is None.

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. 如果 s 参数为 null,是空字符串 ("") 或者不包含日期和时间的有效字符串表示形式,则转换失败。The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. 此参数未经初始化即被传递。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).

provider 是一个非特定区域性,并且不能在分析操作中使用。provider is a neutral culture and cannot be used in a parsing operation.

示例

下面的示例演示 DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 方法。The following example illustrates the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString;
      CultureInfo culture;
      DateTimeStyles styles;
      DateTime dateResult;
      
      // Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", 
                           dateString);
      
      // Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal;
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      
      // Parse a date and time that is assumed to be local.
      // This time is five hours behind UTC. The local system's time zone is 
      // eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00";
      styles = DateTimeStyles.AssumeLocal;
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      
      // Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00";
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);

      // Assume a date and time string formatted for the fr-FR culture is the local 
      // time and convert it to UTC.
      dateString = "2008-03-01 10:00";
      culture = CultureInfo.CreateSpecificCulture("fr-FR");
      styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);

   }
}
// The example displays the following output to the console:
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
//       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
//       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
//       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim dateString As String
      Dim culture As CultureInfo
      Dim styles As DateTimeStyles 
      Dim dateResult As DateTime
      
      ' Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM"
      culture = CultureInfo.CreateSpecificCulture("en-US")
      styles = DateTimeStyles.None
      If DateTime.TryParse(dateString, culture, styles, dateResult) Then
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, dateResult, dateResult.Kind)
      Else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End If      
      
      ' Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal
      If DateTime.TryParse(dateString, culture, styles, dateResult)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, dateResult, dateResult.Kind)
      Else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End If      
      
      ' Parse a date and time that is assumed to be local.
      ' This time is five hours behind UTC. The local system's time zone is 
      ' eight hours behind UTC.
      dateString = "2009/03/01T10:00:00-5:00"
      styles = DateTimeStyles.AssumeLocal
      If DateTime.TryParse(dateString, culture, styles, dateResult)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, dateResult, dateResult.Kind)
      Else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End If      
      
      ' Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00"
      If DateTime.TryParse(dateString, culture, styles, dateResult)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, dateResult, dateResult.Kind)
      Else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End If      

      ' Assume a date and time string formatted for the fr-FR culture is the local 
      ' time and convert it to UTC.
      dateString = "2008-03-01 10:00"
      culture = CultureInfo.CreateSpecificCulture("fr-FR")
      styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
      If DateTime.TryParse(dateString, culture, styles, dateResult)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, dateResult, dateResult.Kind)
      Else
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End If      
   End Sub
End Module
' The example displays the following output to the console:
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
'       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
'       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
'       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.

注解

@No__t-0 方法分析可包含日期、时间和时区信息的字符串。The DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method parses a string that can contain date, time, and time zone information. 它与 DateTime.Parse(String, IFormatProvider, DateTimeStyles) 方法类似,不同的是,如果转换失败,DateTime.TryParse(String, DateTime) 方法不会引发异常。It is similar to the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method, except that the DateTime.TryParse(String, DateTime) method does not throw an exception if the conversion fails.

此方法尝试忽略无法识别的数据,并完全分析 sThis method attempts to ignore unrecognized data and parse s completely. 如果 s 包含时间而不包含日期,则默认情况下该方法将替换当前日期; 如果 styles 包含 @no__t 2 标志,则它将替换为 DateTime.Date.MinValueIf s contains a time but no date, the method by default substitutes the current date or, if styles includes the NoCurrentDateDefault flag, it substitutes DateTime.Date.MinValue. 如果 s 包含日期但没有时间,则使用12:00 午夜作为默认时间。If s contains a date but no time, 12:00 midnight is used as the default time. 如果存在日期但其年份组成部分只包含两个数字,则会根据 Calendar.TwoDigitYearMax 属性的值将其转换为 @no__t 0 参数的当前日历中的年份。If a date is present but its year component consists of only two digits, it is converted to a year in the provider parameter's current calendar based on the value of the Calendar.TwoDigitYearMax property. @No__t-0 中的所有前导、内部或尾随空格字符将被忽略。Any leading, inner, or trailing white space characters in s are ignored. 日期和时间可以用一对前导和尾随数字符号字符("#"、U + 0023)括起来,并且可以使用一个或多个 NULL 字符(U + 0000)进行 trailed。The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).

日期和时间元素的特定有效格式以及日期和时间中使用的名称和符号由 provider 参数定义,该参数可以是以下任一项:Specific valid formats for date and time elements, as well as the names and symbols used in dates and times, are defined by the provider parameter, which can be any of the following:

如果 providernull,则使用当前区域性。If provider is null, the current culture is used.

如果 @no__t 为当前日历中闰年的闰年的字符串表示形式,则该方法将成功分析 @no__t。If s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. 如果 @no__t 为 @no__t 的当前日历中非闰年的闰日的字符串表示形式,则分析操作将失败,并且该方法将返回 falseIf s is the string representation of a leap day in a non-leap year in the current calendar of provider, the parse operation fails and the method returns false.

@No__t 的参数定义分析的字符串的精确解释,以及分析操作应该如何处理它。The styles parameter defines the precise interpretation of the parsed string and how the parse operation should handle it. 它可以是 @no__t 枚举的一个或多个成员,如下表中所述。It can be one or more members of the DateTimeStyles enumeration, as described in the following table.

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 虽然有效,但会忽略此值。Although valid, this value is ignored. @No__t-0 的日期和时间元素中允许有内部空格。Inner white space is permitted in the date and time elements of s.
AllowLeadingWhite 虽然有效,但会忽略此值。Although valid, this value is ignored. @No__t-0 的日期和时间元素中允许使用前导空格。Leading white space is permitted in the date and time elements of s.
AllowTrailingWhite 虽然有效,但会忽略此值。Although valid, this value is ignored. @No__t-0 的日期和时间元素中允许尾随空格。Trailing white space is permitted in the date and time elements of s.
AllowWhiteSpaces 指定 s 可以包含前导空格和尾随空格。Specifies that s may contain leading, inner, and trailing white spaces. 这是默认行为。This is the default behavior. 不能通过提供限制性更强的 DateTimeStyles 枚举值(如 DateTimeStyles.None)来重写它。It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value such as DateTimeStyles.None.
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.
None 虽然有效,但会忽略此值。Although valid, this value is ignored.
RoundtripKind 对于包含时区信息的字符串,尝试防止将日期和时间字符串转换为 DateTime 值,并将其 @no__t 属性设置为 DateTimeKind.LocalFor strings that contain time zone information, tries to prevent the conversion of a date and time string to a DateTime value with its Kind property set to DateTimeKind.Local. 通常,此类字符串是通过使用 "o"、"r" 或 "u" 标准格式说明符调用 DateTime.ToString(String) 方法创建的。Typically, such a string is created by calling the DateTime.ToString(String) method using either the "o", "r", or "u" standard format specifiers.

如果 s 不包含时区信息,DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 方法将返回一个 @no__t 2 值,其 @no__t 3 属性为 DateTimeKind.Unspecified,除非 @no__t 标志为,否则为。If s contains no time zone information, the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method returns a DateTime value whose Kind property is DateTimeKind.Unspecified unless a styles flag indicates otherwise. 如果 s 包括时区或时区偏移量信息,DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 方法将执行任何所需的时间转换,并返回以下内容之一:If s includes time zone or time zone offset information, the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method performs any necessary time conversion and returns one of the following:

此行为可以通过使用 DateTimeStyles.RoundtripKind 标志进行重写。This behavior can be overridden by using the DateTimeStyles.RoundtripKind flag.

分析自定义区域性Parsing Custom Cultures

如果分析为自定义区域性生成的日期和时间字符串,请使用 TryParseExact 方法,而不是 @no__t 方法来提高分析操作成功的概率。If you parse a date and time string generated for a custom culture, use the TryParseExact method instead of the TryParse method to improve the probability that the parse operation will succeed. 自定义区域性日期和时间字符串可能比较复杂且难以分析。A custom culture date and time string can be complicated and difficult to parse. @No__t-0 方法尝试使用几个隐式分析模式分析字符串,所有这些模式都可能失败。The TryParse method attempts to parse a string with several implicit parse patterns, all of which might fail. 与此相反,TryParseExact 方法要求您显式指定一个或多个可能成功的完全分析模式。In contrast, the TryParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed.

有关自定义区域性的详细信息,请参阅 System.Globalization.CultureAndRegionInfoBuilder 类。For more information about custom cultures, see the System.Globalization.CultureAndRegionInfoBuilder class.

调用方说明

格式设置受当前 DateTimeFormatInfo 对象的属性影响,该对象由 provider 参数提供。Formatting is influenced by properties of the current DateTimeFormatInfo object, which is supplied by the provider parameter. 如果当前 @no__t 和 @no__t 属性设置为相同的值,TryParse 方法可能会意外失败并返回 FalseThe TryParse method can unexpectedly fail and return False if the current DateSeparator and TimeSeparator properties are set to the same value.

另请参阅

TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime)

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParse (ReadOnlySpan<char> s, out DateTime result);
static member TryParse : ReadOnlySpan<char> * DateTime -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As DateTime) As Boolean

参数

返回

适用于