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(으)로 변환하고 변환에 성공했는지를 나타내는 값을 반환합니다.

설명

중요

일본어 달력의 시대는 천황 통치 기간을 기준으로 하므로 변경되어야 합니다. 예를 들어 2019년 5월 1일은 JapaneseCalendarJapaneseLunisolarCalendar에서 레이와 시대의 시작을 나타냅니다. 이러한 시대 변경 내용은 해당 달력을 사용하는 모든 애플리케이션에 영향을 줍니다. 자세한 내용과 애플리케이션이 영향을 받는지 여부를 확인하려면 .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

이 메서드가 반환될 때 변환에 성공한 경우 에 s포함된 날짜 및 시간에 해당하는 값을 포함하거나 변환에 실패한 경우 DateTime.MinValue를 포함합니다DateTime. s 매개 변수가 null이거나, 빈 문자열("")이거나, 날짜 및 시간에 유효한 문자열 표현을 포함하고 있지 않으면 변환에 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

반환

true 매개 변수가 변환되었으면 s이고, 그렇지 않으면 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

이 메서드가 반환될 때 변환에 성공한 경우 에 s포함된 날짜 및 시간에 해당하는 값을 포함하거나 변환에 실패한 경우 DateTime.MinValue를 포함합니다DateTime. s 매개 변수가 null이거나, 빈 문자열("")이거나, 날짜 및 시간에 유효한 문자열 표현을 포함하고 있지 않으면 변환에 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

반환

true 매개 변수가 변환되었으면 s이고, 그렇지 않으면 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) 실패할 경우 메서드가 예외를 throw하지 않습니다.

문자열 s 은 현재 문화권에서 암시적으로 제공되는 현재 DateTimeFormatInfo 개체의 서식 정보를 사용하여 구문 분석됩니다.

이 메서드는 가능한 경우 인식할 수 없는 데이터를 무시하려고 시도하고 누락된 월, 일 및 연도 정보를 현재 날짜로 채웁니다. 날짜와 시간만 포함된 경우 s 이 메서드는 시간이 자정 12:00이라고 가정합니다. 두 자리 연도의 날짜 구성 요소가 포함된 경우 s 속성 값을 Calendar.TwoDigitYearMax 기반으로 현재 문화권의 현재 달력에서 1년으로 변환됩니다. 의 선행, 내부 또는 후행 공백 문자 s 는 무시됩니다. 날짜와 시간은 선행 및 후행 NUMBER SIGN 문자 쌍('#', U+0023)으로 대괄호로 묶을 수 있으며 하나 이상의 NULL 문자(U+0000)로 후행할 수 있습니다.

메서드는 DateTime.TryParse(String, DateTime) 현재 문화권의 서식 규칙을 사용하여 날짜 및 시간의 문자열 표현을 구문 분석하려고 하므로 다른 문화권에서 특정 문자열을 구문 분석하려고 하면 실패하거나 다른 결과를 반환할 수 있습니다. 특정 날짜 및 시간 형식이 다른 로캘에서 구문 분석되는 경우 메서드 또는 메서드의 TryParseExact 오버로드 중 하나를 사용하고 DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 형식 지정자를 제공합니다.

가 현재 달력에서 윤년의 윤일 문자열 표현이면 s 메서드가 성공적으로 구문 분석됩니다 s . 가 현재 문화권의 현재 달력에서 윤년이 아닌 연도의 윤일 문자열 표현인 경우 s 구문 분석 작업이 실패하고 메서드가 를 반환합니다 false.

표준 시간대 정보를 포함하지 않는 경우 s 에는 메서드가 DateTime 반환할 때 속성이 인 Kind 값이 포함됩니다DateTimeKind.Unspecified. result 구문 분석할 문자열에 표준 시간대 정보가 result 포함된 경우 메서드가 DateTime 반환될 때 속성이 인 Kind 값이 포함됩니다 DateTimeKind.Local .

호출자 참고

서식 지정은 기본적으로 제어판 국가 및 언어 옵션 항목에서 파생되는 현재 DateTimeFormatInfo 개체의 속성에 의해 영향을 받습니다. 메서드가 TryParse 예기치 않게 실패하고 현재 DateSeparatorTimeSeparator 속성이 동일한 값으로 설정된 경우 를 반환 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

이 메서드가 반환될 때 변환에 성공한 경우 에 s포함된 날짜 및 시간에 해당하는 값을 포함하거나 변환에 실패한 경우 DateTime.MinValue를 포함합니다DateTime. s 매개 변수가 null이거나, 빈 문자열("")이거나, 날짜 및 시간에 유효한 문자열 표현을 포함하고 있지 않으면 변환에 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

반환

true 매개 변수가 변환되었으면 s이고, 그렇지 않으면 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.

설명

이 API에 대한 자세한 내용은 DateTime.TryParse에 대한 추가 API 설명을 참조하세요.

호출자 참고

서식 지정은 매개 변수에서 제공하는 현재 DateTimeFormatInfo 개체의 속성에 의해 영향을 받습니다 provider . 메서드가 TryParse 예기치 않게 실패하고 현재 DateSeparatorTimeSeparator 속성이 동일한 값으로 설정된 경우 를 반환 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

이 메서드가 반환될 때 변환에 성공한 경우 에 s포함된 날짜 및 시간에 해당하는 값을 포함하거나 변환에 실패한 경우 DateTime.MinValue를 포함합니다DateTime. s 매개 변수가 null이거나, 빈 문자열("")이거나, 날짜 및 시간에 유효한 문자열 표현을 포함하고 있지 않으면 변환에 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

반환

true 매개 변수가 변환되었으면 s이고, 그렇지 않으면 false입니다.

적용 대상