DateTime.TryParse メソッド

定義

指定した文字列形式の日時を対応する DateTime 表現に変換し、変換に成功したかどうかを示す値を返します。

オーバーロード

TryParse(ReadOnlySpan<Char>, DateTime)

指定した日付と時刻の文字スパンを、それと等価な DateTime に変換し、変換が成功したかどうかを示す値を返します。

TryParse(String, DateTime)

指定した文字列形式の日時を対応する DateTime 表現に変換し、変換に成功したかどうかを示す値を返します。

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTime)

文字のスパンを値に解析しようとします。

TryParse(String, IFormatProvider, DateTime)

文字列を値に解析しようとします。

TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

指定したカルチャ固有の書式情報と書式スタイルを使用して、指定した文字列形式の日付と時刻をそれと等価の DateTime に変換し、変換に成功したかどうかを示す値を返します。

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

指定したカルチャ固有の書式情報と書式スタイルを使用して、日付と時刻のスパン表現を、それと等価な DateTime に変換し、変換が成功したかどうかを示す値を返します。

注釈

重要

和暦の時代 (年号) は天皇の代に基づいているため、変更されることが予想されます。 たとえば、JapaneseCalendarJapaneseLunisolarCalendar において、2019 年 5 月 1 日から令和時代が始まることになりました。 このような時代 (年号) の変更は、これらのカレンダーを使用するすべてのアプリケーションに影響します。 詳細と、アプリケーションが影響を受けるかどうかを判断するには、「 .NET での日本語カレンダーでの新しい時代の処理」を参照してください。 Windows システムでアプリケーションをテストして時代 (年号) の変更に対する準備を確認する方法については、「 日本の時代 (年号) に合わせてアプリケーションを準備する」を参照してください。 複数の時代 (年号) を含むカレンダーをサポートする .NET の機能と、複数の時代 (年号) をサポートするカレンダーを操作する場合のベスト プラクティスについては、「 年号の操作」を参照してください。

TryParse(ReadOnlySpan<Char>, DateTime)

指定した日付と時刻の文字スパンを、それと等価な 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

パラメーター

s
ReadOnlySpan<Char>

変換する日付と時刻を格納した文字列。

result
DateTime

このメソッドが戻るとき、 には、 に含まれる日付と時刻に相当する値が格納DateTimesされます (変換が成功した場合は )。 変換に失敗した場合は DateTime.MinValue が格納されます。 s パラメーターが null の場合、空の文字列 ("") の場合、または日付と時刻を表す有効な文字列形式が含まれていない場合は、変換に失敗します。 このパラメーターは初期化せずに渡されます。

戻り値

s パラメーターが正常に変換された場合は true。それ以外の場合は false

適用対象

TryParse(String, DateTime)

指定した文字列形式の日時を対応する DateTime 表現に変換し、変換に成功したかどうかを示す値を返します。

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] DateTime % result);
public static bool TryParse (string s, 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

変換する日付と時刻を格納した文字列。

result
DateTime

このメソッドが戻るとき、 には、 に含まれる日付と時刻に相当する値が格納DateTimesされます (変換が成功した場合は )。 変換に失敗した場合は DateTime.MinValue が格納されます。 s パラメーターが null の場合、空の文字列 ("") の場合、または日付と時刻を表す有効な文字列形式が含まれていない場合は、変換に失敗します。 このパラメーターは初期化せずに渡されます。

戻り値

s パラメーターが正常に変換された場合は true。それ以外の場合は false

次の例では、日付と時刻の文字列の数を メソッドに DateTime.TryParse(String, DateTime) 渡します。

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).
open System
open System.Globalization

let 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" ]

printfn $"Attempting to parse strings using {CultureInfo.CurrentCulture.Name} culture."
for dateString in dateStrings do
    match DateTime.TryParse dateString with
    | true, dateValue ->
        printfn $"  Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    | _ ->
        printfn $"  Unable to parse '{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) メソッドは例外をスローしません。

文字列 s は、現在のカルチャによって暗黙的に提供される現在 DateTimeFormatInfo のオブジェクトの書式設定情報を使用して解析されます。

このメソッドは、可能であれば認識できないデータを無視し、不足している月、日、および年の情報を現在の日付で入力します。 日付のみを含み、時刻がない場合 s 、このメソッドは時刻が午前 0 時 12 分であると想定します。 2 桁の年を持つ日付コンポーネントが含まれている場合 s 、プロパティの値に基づいて、現在のカルチャの現在のカレンダーの年に Calendar.TwoDigitYearMax 変換されます。 の先頭、内側、または末尾の s 空白文字は無視されます。 日付と時刻は、先頭と末尾の NUMBER SIGN 文字 ('#'、 U+0023) のペアで角かっこで囲むことができます。また、1 つ以上の NULL 文字 (U+0000) で後に続けることができます。

メソッドは現在の DateTime.TryParse(String, DateTime) カルチャの書式設定規則を使用して日付と時刻の文字列表現を解析しようとするため、異なるカルチャ間で特定の文字列を解析しようとすると、失敗するか、異なる結果が返される可能性があります。 特定の日付と時刻の形式が異なるロケールで解析される場合は、 メソッドまたは メソッドのいずれかのオーバーロードTryParseExactを使用DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)し、書式指定子を指定します。

が現在のカレンダーの閏年の閏日の文字列表現である場合 s 、メソッドは正常に解析されます s 。 が現在のカルチャの現在のカレンダーで閏年以外の閏日の文字列表現である場合 s 、解析操作は失敗し、 メソッドは を返します false

タイム ゾーン情報が含まれない場合sは、 result メソッドが返されるときに プロパティが DateTimeKind.Unspecified である値Kindを格納DateTimeします。 解析される文字列にタイム ゾーン情報が含まれている場合は、 result メソッドが返されたときの Kind プロパティDateTimeKind.Localを持つ値が含DateTimeまれます。

注意 (呼び出し元)

書式設定は、現在DateTimeFormatInfoのオブジェクトのプロパティの影響を受けます。既定では、コントロール パネルの [地域と言語のオプション] 項目から派生します。 メソッドがTryParse予期せず失敗し、現在DateSeparatorの プロパティとTimeSeparatorプロパティが同じ値に設定されている場合は が返Falseされる可能性があります。

こちらもご覧ください

適用対象

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTime)

文字のスパンを値に解析しようとします。

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

パラメーター

s
ReadOnlySpan<Char>

解析する文字のスパン。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

result
DateTime

このメソッドが返されると、 には、正常に解析 sされた結果、または失敗した場合に未定義の値が格納されます。

戻り値

true が正常に解析された場合 s は 。それ以外の場合 falseは 。

適用対象

TryParse(String, IFormatProvider, DateTime)

文字列を値に解析しようとします。

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

パラメーター

s
String

解析する文字列。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

result
DateTime

このメソッドが戻ったとき、 には、正常に解析 s された結果または失敗した場合に未定義の値が含まれます。

戻り値

true が正常に解析された場合 s は 。それ以外の場合 falseは 。

適用対象

TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

指定したカルチャ固有の書式情報と書式スタイルを使用して、指定した文字列形式の日付と時刻をそれと等価の DateTime に変換し、変換に成功したかどうかを示す値を返します。

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);
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

変換する日付と時刻を格納した文字列。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

現在のタイム ゾーンまたは現在の日付と関連させて、解析された日付をどのように解釈するかを定義する列挙値のビットごとの組み合わせ。 通常指定する値は、None です。

result
DateTime

このメソッドが戻るとき、 には、 に含まれる日付と時刻に相当する値が格納DateTimesされます (変換が成功した場合は )。 変換に失敗した場合は DateTime.MinValue が格納されます。 s パラメーターが null の場合、空の文字列 ("") の場合、または日付と時刻を表す有効な文字列形式が含まれていない場合は、変換に失敗します。 このパラメーターは初期化せずに渡されます。

戻り値

s パラメーターが正常に変換された場合は true。それ以外の場合は false

例外

styles は有効な DateTimeStyles 値ではありません。

または

stylesDateTimeStyles 値の正しくない組み合わせが含まれています (たとえば、AssumeLocalAssumeUniversal の両方などです)。

provider はニュートラル カルチャであり、解析操作で使用することはできません。

次の例は、 メソッドを DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 示しています。

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.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Parse a date and time with no styles.
    let dateString = "03/01/2009 10:00 AM"
    let culture = CultureInfo.CreateSpecificCulture "en-US"
    let styles = DateTimeStyles.None
    match DateTime.TryParse(dateString, culture, styles) with
    | true, dateResult ->
        printfn $"{dateString} converted to {dateResult} {dateResult.Kind}."
    | _ -> 
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse the same date and time with the AssumeLocal style.
    let styles = DateTimeStyles.AssumeLocal
    match DateTime.TryParse(dateString, culture, styles) with
    | true, dateResult ->
        printfn $"{dateString} converted to {dateResult} {dateResult.Kind}." 
    | _ ->
        printfn $"Unable to convert {dateString} to a date and time."

    // 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.
    let dateString = "2009/03/01T10:00:00-5:00"
    let styles = DateTimeStyles.AssumeLocal
    match DateTime.TryParse(dateString, culture, styles) with
    | true, dateResult ->
        printfn $"{dateString} converted to {dateResult} {dateResult.Kind}."
    | _ ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Attempt to convert a string in improper ISO 8601 format.
    let dateString = "03/01/2009T10:00:00-5:00"
    match DateTime.TryParse(dateString, culture, styles) with
    | true, dateResult ->
        printfn $"{dateString} converted to {dateResult} {dateResult.Kind}."
    | _ ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Assume a date and time string formatted for the fr-FR culture is the local
    // time and convert it to UTC.
    let dateString = "2008-03-01 10:00"
    let culture = CultureInfo.CreateSpecificCulture "fr-FR"
    let styles = DateTimeStyles.AdjustToUniversal ||| DateTimeStyles.AssumeLocal
    match DateTime.TryParse(dateString, culture, styles) with
    | true, dateResult ->
        printfn $"{dateString} converted to {dateResult} {dateResult.Kind}." 
    | _ ->
        printfn $"Unable to convert {dateString} to a date and time."

    0

// 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) 、日付、時刻、タイム ゾーンの情報を含むことができる文字列を解析します。 メソッドと似ています DateTime.Parse(String, IFormatProvider, DateTimeStyles) が、変換が失敗した場合、 DateTime.TryParse(String, DateTime) メソッドは例外をスローしません。

このメソッドは、認識されないデータを無視し、完全に解析 s しようとします。 時刻が含まれているが日付が含まれない場合s、メソッドは既定で現在の日付を置き換えるか、フラグがNoCurrentDateDefault含まれている場合stylesは にDateTime.Date.MinValue置き換えられます。 日付が含まれているが時刻がない場合 s は、12:00 の午前 0 時が既定の時刻として使用されます。 日付が存在するが、その年のコンポーネントが 2 桁の数字のみで構成されている場合、プロパティの値に基づいて、パラメーターの現在のカレンダーの provider 年に Calendar.TwoDigitYearMax 変換されます。 の先頭、内側、または末尾の s 空白文字は無視されます。 日付と時刻は、先頭と末尾の NUMBER SIGN 文字 ('#'、 U+0023) のペアで角かっこで囲むことができます。また、1 つ以上の NULL 文字 (U+0000) で後に続けることができます。

日付と時刻の要素の特定の有効な形式、および日付と時刻で使用される名前と記号は、 パラメーターによって provider 定義されます。パラメーターは次のいずれかになります。

providernull の場合は、現在のカルチャが使用されます。

が現在のカレンダーの閏年の閏日の文字列表現である場合 s 、メソッドは正常に解析されます s 。 が の現在のカレンダーで閏年以外の閏日のprovider文字列表現である場合s、解析操作は失敗し、 メソッドは を返しますfalse

パラメーターは styles 、解析された文字列の正確な解釈と、解析操作で処理する方法を定義します。 次の表に示すように、列挙体の DateTimeStyles 1 つ以上のメンバーを指定できます。

DateTimeStyles メンバー 説明
AdjustToUniversal sを解析し、必要に応じて UTC に変換します。 タイム ゾーン オフセットが含まれている場合s、またはタイム ゾーン情報が含まれないが フラグがstyles含まれているDateTimeStyles.AssumeLocal場合s、メソッドは文字列を解析し、 を呼び出ToUniversalTimeして戻りDateTime値を UTC に変換し、 プロパティを KindDateTimeKind.Utc設定します。 が UTC を表していることを示す場合s、またはタイム ゾーン情報が含まれていないがフラグがstyles含まれているDateTimeStyles.AssumeUniversal場合s、メソッドは文字列を解析し、返されたDateTime値に対してタイム ゾーン変換を実行せず、 プロパティを KindDateTimeKind.Utc設定します。 それ以外の場合、フラグは無効です。
AllowInnerWhite 有効ですが、この値は無視されます。 の日付と時刻の要素 sでは、内側の空白を使用できます。
AllowLeadingWhite 有効ですが、この値は無視されます。 の日付と時刻の要素 sでは、先頭の空白を使用できます。
AllowTrailingWhite 有効ですが、この値は無視されます。 末尾の空白は、 の日付と時刻の s要素で使用できます。
AllowWhiteSpaces 先頭、 s 内側、末尾に空白を含めることができます。 これが既定の動作です。 などのDateTimeStyles.Noneより制限の厳DateTimeStylesしい列挙値を指定してオーバーライドすることはできません。
AssumeLocal タイム ゾーン情報がない場合 s は、現地時刻を表すと見なされることを指定します。 フラグがDateTimeStyles.AdjustToUniversal存在しない限り、Kind戻り値の プロパティは にDateTimeKind.Local設定されますDateTime
AssumeUniversal タイム ゾーン情報がない場合 s は、UTC を表すと見なされることを指定します。 フラグが DateTimeStyles.AdjustToUniversal 存在しない限り、 メソッドは返された DateTime 値を UTC から現地時刻に変換し、そのプロパティを KindDateTimeKind.Local設定します。
None 有効ですが、この値は無視されます。
RoundtripKind タイム ゾーン情報を含む文字列の場合、そのプロパティが に設定DateTimeKind.Localされた値KindへのDateTime日付と時刻の文字列の変換を回避しようとします。 通常、このような文字列は、"o"、"r"、または "u" 標準書式指定子を使用して メソッドを呼び出 DateTime.ToString(String) すことによって作成されます。

タイム ゾーン情報が含まれない場合s、 メソッドは、DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)フラグが特にDateTime示さない限り、 プロパティが DateTimeKind.Unspecified である値Kindstyles返します。 タイム ゾーンまたはタイム ゾーン オフセット情報が含まれている場合 s 、メソッドは DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 必要な時刻変換を実行し、次のいずれかを返します。

この動作は、 フラグを使用 DateTimeStyles.RoundtripKind してオーバーライドできます。

カスタム カルチャの解析

カスタム カルチャに対して生成された日付と時刻の文字列を解析する場合は、 メソッドの代わりに メソッドをTryParse使用TryParseExactして、解析操作が成功する可能性を高めます。 カスタム カルチャの日付と時刻の文字列は複雑で解析が困難な場合があります。 メソッドは TryParse 、いくつかの暗黙的な解析パターンを使用して文字列の解析を試みますが、そのすべてが失敗する可能性があります。 これに対し、 メソッドでは TryParseExact 、成功する可能性が高い 1 つ以上の正確な解析パターンを明示的に指定する必要があります。

カスタム カルチャの詳細については、 クラスを System.Globalization.CultureAndRegionInfoBuilder 参照してください。

注意 (呼び出し元)

書式設定は、 パラメーターによって提供される現在 DateTimeFormatInfo のオブジェクトのプロパティの影響を provider 受けます。 メソッドがTryParse予期せず失敗し、現在DateSeparatorの プロパティとTimeSeparatorプロパティが同じ値に設定されている場合は が返Falseされる可能性があります。

こちらもご覧ください

適用対象

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

指定したカルチャ固有の書式情報と書式スタイルを使用して、日付と時刻のスパン表現を、それと等価な 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);
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>

変換する日付と時刻を表す文字を含むスパン。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

現在のタイム ゾーンまたは現在の日付と関連させて、解析された日付をどのように解釈するかを定義する列挙値のビットごとの組み合わせ。 通常指定する値は、None です。

result
DateTime

このメソッドが戻るとき、 には、 に含まれる日付と時刻に相当する値が格納DateTimesされます (変換が成功した場合は )。 変換に失敗した場合は DateTime.MinValue が格納されます。 s パラメーターが null の場合、空の文字列 ("") の場合、または日付と時刻を表す有効な文字列形式が含まれていない場合は、変換に失敗します。 このパラメーターは初期化せずに渡されます。

戻り値

s パラメーターが正常に変換された場合は true。それ以外の場合は false

適用対象