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)

使用指定的特定文化特性格式資訊和格式樣式,以將日期和時間的範圍表示轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the span 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(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)

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the specified char span of a date and time to its DateTime equivalent and 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 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 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)

使用指定的特定文化特性格式資訊和格式樣式,以將日期和時間的範圍表示轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the span 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(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);
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

參數

s
ReadOnlySpan<Char>

包含字元的範圍,其表示要轉換的日期和時間。A span containing the characters representing the 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.

傳回

Boolean

如果 true 參數轉換成功,則為 s,否則為 falsetrue if the s parameter was converted successfully; otherwise, false.

適用於

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.

傳回

Boolean

如果 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).

備註

DateTime.TryParse(String, DateTime)方法與 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.

如果可能的話,這個方法會嘗試忽略無法辨識的資料,並以目前的日期填滿遺漏的 month、day 和 year 資訊。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.TwoDigitYearMaxIf 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. 中的任何前置、內部或尾端空白字元都會被 s 忽略。Any leading, inner, or trailing white space character in s is ignored. 日期和時間可以用一對開頭和尾端數位記號字元括住 ( ' # '、U + 0023) ,而且可以使用一或多個 Null 字元來 trailed, (U + 0000) 。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) 方法或方法的其中一個多載, TryParseExact 並提供格式規範。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 是目前行事曆之閏年中的閏日字串標記法,則方法會 s 成功剖析。If 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 包含 DateTimeKind 屬性是在方法傳回時的值 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.

給呼叫者的注意事項

格式設定會受到目前物件的屬性所影響 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. TryParse False 如果目前的 DateSeparatorTimeSeparator 屬性設定為相同的值,方法可能會意外失敗並傳回。The 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.

傳回

Boolean

如果 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.

備註

DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)方法會剖析可包含日期、時間和時區資訊的字串。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.

這個方法會嘗試忽略無法辨識的資料並 s 完全剖析。This 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. 如果有日期存在,但其 year 元件僅包含兩位數,則會根據屬性的值,將它轉換成參數目前行事曆中的年份 provider Calendar.TwoDigitYearMaxIf 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. 中的任何前置、內部或尾端空白字元都會被 s 忽略。Any leading, inner, or trailing white space characters in s are ignored. 日期和時間可以用一對開頭和尾端數位記號字元括住 ( ' # '、U + 0023) ,而且可以使用一或多個 Null 字元來 trailed, (U + 0000) 。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 是目前行事曆之閏年中的閏日字串標記法,則方法會 s 成功剖析。If s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. 如果 s 是目前行事曆之非閏年的閏日字串表示 provider ,則剖析作業會失敗,且方法會傳回 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.

styles參數會定義剖析字串的精確轉譯,以及剖析作業應該如何處理它。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 將傳回值轉換為 UTC 的呼叫, DateTime 並將 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 並將屬性設定 KindDateTimeKind.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. 在的日期和時間元素中,允許內部的空白字元 sInner white space is permitted in the date and time elements of s.
AllowLeadingWhite 雖然有效,但會忽略此值。Although valid, this value is ignored. 的日期和時間元素中允許前置空白字元 sLeading white space is permitted in the date and time elements of s.
AllowTrailingWhite 雖然有效,但會忽略此值。Although valid, this value is ignored. 的日期和時間元素中允許尾端空白字元 sTrailing 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.NoneIt 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 有旗標,否則 Kind 傳回值的屬性 DateTime 會設定為 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 如果是包含時區資訊的字串,則會嘗試避免將日期和時間字串轉換成值, DateTime 並將其 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. 一般而言,這類字串是藉由 DateTime.ToString(String) 使用 "o"、"r" 或 "u" 標準格式規範來呼叫方法來建立。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) 方法 DateTime 會傳回屬性為的值, Kind DateTimeKind.Unspecified 除非旗標 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 包含時區或時區時差資訊,則此 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.RoundtripKindThis 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. TryParse方法會嘗試剖析具有數個隱含剖析模式的字串,而這些模式都可能會失敗。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 物件(由參數提供)的屬性所影響 providerFormatting is influenced by properties of the current DateTimeFormatInfo object, which is supplied by the provider parameter. TryParse False 如果目前的 DateSeparatorTimeSeparator 屬性設定為相同的值,方法可能會意外失敗並傳回。The 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)

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the specified char span of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

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

參數

s
ReadOnlySpan<Char>

字串,含有要轉換的日期和時間。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.

傳回

Boolean

如果 true 參數轉換成功,則為 s,否則為 falsetrue if the s parameter was converted successfully; otherwise, false.

適用於