DateTime.TryParse 方法

定義

將日期和時間的指定字串表示,轉換為其相等的 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(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)

使用指定的特定文化特性格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其相等的 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)

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 Prepare your application for the Japanese era change (讓應用程式準備好因應日本紀元變更)。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 請參閱使用紀年以了解 .NET 中支援使用多種紀年的日曆,以及在處理支援多種紀年的日曆時能採用最佳做法。See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

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

參數

provider
IFormatProvider
result
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

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

result
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) 方法,不同之處在于如果轉換失敗,則 @no__t 2 方法不會擲回例外狀況。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.

@No__t-0 的字串會使用目前的 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).

因為 DateTime.TryParse(String, DateTime) 方法會嘗試使用目前文化特性的格式化規則來剖析日期和時間的字串標記法,所以嘗試剖析不同文化特性的特定字串可能會失敗或傳回不同的結果。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 1 方法的其中一個多載,並提供格式規範。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.

如果 s 是目前行事曆的閏年中,閏日的字串標記法,則方法會成功剖析 sIf s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. 如果 s 是目前文化特性之目前行事曆的非閏年中,閏日的字串標記法,則剖析作業會失敗,且方法會傳回 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 會包含 DateTime 值,當方法傳回時,其 Kind 屬性會 DateTimeKind.UnspecifiedIf s contains no time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Unspecified when the method returns. 如果要剖析的字串包含時區資訊,result 包含 DateTime 值,當方法傳回時,其 Kind 屬性會 DateTimeKind.LocalIf the string to be parsed contains time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Local when the method returns.

給呼叫者的注意事項

格式設定會受到目前 @no__t 0 物件的屬性影響,預設是從 [控制台] 中的 [地區及語言選項] 專案衍生而來。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. 如果目前的 DateSeparatorTimeSeparator 屬性設定為相同的值,則 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)

使用指定的特定文化特性格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其相等的 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

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

provider
IFormatProvider

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

styles
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 中內含之日期與時間相等的 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) 方法,不同之處在于如果轉換失敗,@no__t 1 方法不會擲回例外狀況。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 包含 NoCurrentDateDefault 旗標,則會取代 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.

如果 s 是目前行事曆的閏年中,閏日的字串標記法,則方法會成功剖析 sIf s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. 如果 sprovider 之目前行事曆中非閏年的閏年字串表示,則剖析作業會失敗,且方法會傳回 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-0 參數會定義剖析字串的精確轉譯,以及剖析作業應該如何處理它。The styles parameter defines the precise interpretation of the parsed string and how the parse operation should handle it. 它可以是 DateTimeStyles 列舉的一個或多個成員,如下表所述。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 不包含時區資訊,但 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 雖然有效,但會忽略這個值。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 值的 Kind 屬性會設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.
AssumeUniversal 指定如果 s 缺少任何時區資訊,則會假設為表示 UTC。Specifies that if s lacks any time zone information, it is assumed to represent UTC. 除非有 DateTimeStyles.AdjustToUniversal 旗標,否則方法會將傳回的 DateTime 值從 UTC 轉換為當地時間,並將其 Kind 屬性設定為 DateTimeKind.LocalUnless the DateTimeStyles.AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.
None 雖然有效,但會忽略這個值。Although valid, this value is ignored.
RoundtripKind 對於包含時區資訊的字串,會嘗試防止將日期和時間字串轉換為 @no__t 0 值,並將其 Kind 屬性設定為 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) 方法會傳回其 Kind 屬性為 DateTimeKind.UnspecifiedDateTime 值,除非 styles 旗標另有指示。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 包含時區或時區時差資訊,則 @no__t 1 方法會執行任何必要的時間轉換,並傳回下列其中一項: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 方法來取代 TryParse 方法,以改善剖析作業成功的機率。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. 如果目前的 DateSeparatorTimeSeparator 屬性設定為相同的值,則 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)

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

參數

result
DateTime

傳回

適用於