DateTime.ParseExact 메서드

정의

날짜 및 시간에 대한 지정된 문자열 표현을 해당 DateTime으로 변환합니다. 문자열 표현의 형식은 지정된 형식과 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

오버로드

ParseExact(String, String, IFormatProvider)

지정된 형식 및 문화권별 형식 정보를 사용하여 날짜 및 시간의 지정된 문자열 표현을 해당 DateTime으로 변환합니다. 문자열 표현의 형식이 지정된 형식과 정확하게 일치해야 합니다.

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

지정된 형식, 문화권별 형식 정보 및 스타일을 사용하여 날짜 및 시간의 지정된 범위 표현을 해당하는 DateTime(으)로 변환합니다. 문자열 표현의 서식은 지정된 서식과 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)

지정된 형식 배열, 문화권별 형식 정보 및 스타일을 사용하여 지정된 날짜와 시간의 범위 표현을 해당하는 DateTime(으)로 변환합니다. 문자열 표현의 서식은 지정된 형식 중 최소한 하나와 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

ParseExact(String, String, IFormatProvider, DateTimeStyles)

지정된 형식, 문화권별 형식 정보 및 스타일을 사용하여 날짜 및 시간의 지정된 문자열 표현을 해당 DateTime으로 변환합니다. 문자열 표현의 서식은 지정된 서식과 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

ParseExact(String, String[], IFormatProvider, DateTimeStyles)

지정된 형식 배열, 문화권별 형식 정보 및 스타일을 사용하여 지정된 날짜와 시간의 문자열 표현을 해당 DateTime 표현으로 변환합니다. 문자열 표현의 서식은 지정된 형식 중 최소한 하나와 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

설명

중요

일본어 달력의 시대는 천황 통치 기간을 기준으로 하므로 변경되어야 합니다. 예를 들어 2019년 5월 1일은 JapaneseCalendarJapaneseLunisolarCalendar에서 레이와 시대의 시작을 나타냅니다. 이러한 시대 변경 내용은 해당 달력을 사용하는 모든 애플리케이션에 영향을 줍니다. 자세한 내용 및 애플리케이션이 영향을 받는지 여부를 확인하려면 .NET에서 일본 달력의 새 시대 처리를참조하세요. Windows 시스템에서 애플리케이션을 테스트하여 시대 변화에 대한 준비 상태를 확인하는 자세한 내용은 일본 연호 변경을 위한 애플리케이션 준비를 참조하세요. 여러 시대가 있는 달력을 지원하는 .NET의 기능 및 여러 연호를 지원하는 달력으로 작업하는 경우 모범 사례는 연호 작업을 참조하세요.

ParseExact(String, String, IFormatProvider)

지정된 형식 및 문화권별 형식 정보를 사용하여 날짜 및 시간의 지정된 문자열 표현을 해당 DateTime으로 변환합니다. 문자열 표현의 형식이 지정된 형식과 정확하게 일치해야 합니다.

public:
 static DateTime ParseExact(System::String ^ s, System::String ^ format, IFormatProvider ^ provider);
public static DateTime ParseExact (string s, string format, IFormatProvider provider);
public static DateTime ParseExact (string s, string format, IFormatProvider? provider);
static member ParseExact : string * string * IFormatProvider -> DateTime
Public Shared Function ParseExact (s As String, format As String, provider As IFormatProvider) As DateTime

매개 변수

s
String

변환할 날짜 및 시간이 포함된 문자열입니다.

format
String

s의 필수 형식을 정의하는 서식 지정자입니다. 자세한 내용은 설명 섹션을 참조하세요.

provider
IFormatProvider

s에 대한 문화권별 서식 지정 정보를 제공하는 개체입니다.

반환

DateTime

sformat에 지정된 내용에 따라 provider에 포함된 날짜 및 시간에 해당하는 개체입니다.

예외

s 또는 formatnull인 경우

s 또는 format가 빈 문자열입니다.

또는

sformat에 지정된 패턴과 일치하는 날짜 및 시간이 포함되어 있지 않습니다.

또는

s의 시간 구성 요소와 AM/PM 지정자가 일치하지 않습니다.

예제

다음 예제는 ParseExact 메서드.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString, format;
      DateTime result;
      CultureInfo provider = CultureInfo.InvariantCulture;

      // Parse date-only value with invariant culture.
      dateString = "06/15/2008";
      format = "d";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date-only value without leading zero in month using "d" format.
      // Should throw a FormatException because standard short date pattern of
      // invariant culture requires two-digit month.
      dateString = "6/15/2008";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date and time with custom specifier.
      dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
      format = "ddd dd MMM yyyy h:mm tt zzz";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date and time with offset but without offset's minutes.
      // Should throw a FormatException because "zzz" specifier requires leading
      // zero in hours.
      dateString = "Sun 15 Jun 2008 8:30 AM -06";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      dateString = "15/06/2008 08:30";
      format = "g";
      provider = new CultureInfo("fr-FR");
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse a date that includes seconds and milliseconds
      // by using the French (France) and invariant cultures.
      dateString = "18/08/2015 06:30:15.006542";
      format = "dd/MM/yyyy HH:mm:ss.ffffff";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }
   }
}
// The example displays the following output:
//       06/15/2008 converts to 6/15/2008 12:00:00 AM.
//       6/15/2008 is not in the correct format.
//       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
//       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
//       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
//       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    let provider = CultureInfo.InvariantCulture

    // Parse date-only value with invariant culture.
    let dateString = "06/15/2008"
    let format = "d"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    // Parse date-only value without leading zero in month using "d" format.
    // Should throw a FormatException because standard short date pattern of
    // invariant culture requires two-digit month.
    let dateString = "6/15/2008"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    // Parse date and time with custom specifier.
    let dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
    let format = "ddd dd MMM yyyy h:mm tt zzz"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    // Parse date and time with offset but without offset's minutes.
    // Should throw a FormatException because "zzz" specifier requires leading
    // zero in hours.
    let dateString = "Sun 15 Jun 2008 8:30 AM -06"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    let dateString = "15/06/2008 08:30"
    let format = "g"
    let provider = CultureInfo "fr-FR"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    // Parse a date that includes seconds and milliseconds
    // by using the French (France) and invariant cultures.
    let dateString = "18/08/2015 06:30:15.006542"
    let format = "dd/MM/yyyy HH:mm:ss.ffffff"
    try
        let result = DateTime.ParseExact(dateString, format, provider)
        printfn $"{dateString} converts to {result}."
    with :? FormatException ->
        printfn $"{dateString} is not in the correct format."

    0

// The example displays the following output:
//       06/15/2008 converts to 6/15/2008 12:00:00 AM.
//       6/15/2008 is not in the correct format.
//       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
//       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
//       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
//       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateString, format As String  
      Dim result As Date
      Dim provider As CultureInfo = CultureInfo.InvariantCulture

      ' Parse date-only value with invariant culture.
      dateString = "06/15/2008"
      format = "d"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 

      ' Parse date-only value without leading zero in month using "d" format.
      ' Should throw a FormatException because standard short date pattern of 
      ' invariant culture requires two-digit month.
      dateString = "6/15/2008"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse date and time with custom specifier.
      dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
      format = "ddd dd MMM yyyy h:mm tt zzz"        
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse date and time with offset but without offset's minutes.
      ' Should throw a FormatException because "zzz" specifier requires leading  
      ' zero in hours.
      dateString = "Sun 15 Jun 2008 8:30 AM -06"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try 
      
      ' Parse a date string using the French (France) culture.
      dateString = "15/06/2008 08:30"
      format = "g"
      provider = New CultureInfo("fr-FR")
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try

      ' Parse a date that includes seconds and milliseconds
      ' by using the French (France) and invariant cultures.
      dateString = "18/08/2015 06:30:15.006542"
      format = "dd/MM/yyyy HH:mm:ss.ffffff"
      Try
         result = Date.ParseExact(dateString, format, provider)
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
      Catch e As FormatException
         Console.WriteLine("{0} is not in the correct format.", dateString)
      End Try
   End Sub
End Module
' The example displays the following output:
'       06/15/2008 converts to 6/15/2008 12:00:00 AM.
'       6/15/2008 is not in the correct format.
'       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
'       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
'       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
'       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.

설명

메서드는 DateTime.ParseExact(String, String, IFormatProvider) 매개 변수에서 정의한 형식이어야 하는 날짜의 문자열 표현을 format 구문 분석합니다. 또한 <Date> 날짜 및 시간의 문자열 표현 및 <Time> 요소가 지정된 format순서대로 표시되어야 하며 s , 허용되는 format공백 이외의 공백이 없어야 합니다. 시간 요소가 없는 날짜를 정의하고 구문 분석 작업에 성공하면 format 결과 DateTime 값은 자정(00:00:00)입니다. 날짜 요소가 없는 시간을 정의하고 구문 분석 작업에 성공하면 format 결과 DateTime 값의 날짜 DateTime.Now.Date가 됩니다.

특정 표준 시간대의 시간을 나타내지 않고 구문 분석 작업이 성공 Kind 하면 s 반환 DateTime 된 값의 속성이 됩니다DateTimeKind.Unspecified. 특정 표준 시간대의 시간을 나타내고 표준 시간대 정보가 표시되도록 허용하는 경우 s format(예: "o", "r" 또는 "u" 표준 형식 지정자와 같거나 "z", "zz" 또는 "zzz" 사용자 지정 형식 지정자가 포함된 경우) Kind 반환 DateTime 된 값의 속성입니다DateTimeKind.Local.format

format 매개 변수는 단일 표준 형식 지정자 또는 필요한 형식을 정의하는 하나 이상의 사용자 지정 형식 지정자를 포함하는 문자열입니다s. 유효한 서식 코드에 대한 자세한 내용은 표준 날짜 및 시간 형식 문자열 또는 사용자 지정 날짜 및 시간 형식 문자열을 참조하세요.

참고

날짜 또는 시간 구분 기호(예: "yyyyMMddHHmm")를 포함하지 않는 사용자 지정 형식 패턴인 경우 format 매개 변수의 고정 문화 provider 권과 각 사용자 지정 형식 지정자의 가장 넓은 형식을 사용합니다. 예를 들어 형식 패턴에서 시간을 지정하려면 더 좁은 형식인 "H" 대신 더 넓은 형식인 "HH"를 지정합니다.

사용되는 특정 날짜 및 시간 기호 및 문자열(예: 특정 언어의 요일 이름)s은 표준 형식 지정자 문자열인 경우 formats 정확한 형식과 마찬가지로 매개 변수에 의해 provider 정의됩니다. 매개 변수는 provider 다음 중 어느 것일 수 있습니다.

nullCultureInfo 경우 provider 현재 문화권에 해당하는 개체가 사용됩니다.

호출자 참고

.NET Framework 4 ParseExact 에서는 구문 분석할 문자열에 시간 구성 요소와 규약이 없는 AM/PM 지정자가 포함된 경우 메서드가 throw FormatException 됩니다. .NET Framework 3.5 이전 버전에서는 AM/PM 지정자가 무시됩니다.

추가 정보

적용 대상

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

지정된 형식, 문화권별 형식 정보 및 스타일을 사용하여 날짜 및 시간의 지정된 범위 표현을 해당하는 DateTime(으)로 변환합니다. 문자열 표현의 서식은 지정된 서식과 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

public static DateTime ParseExact (ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider? provider, System.Globalization.DateTimeStyles style = System.Globalization.DateTimeStyles.None);
public static DateTime ParseExact (ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider provider, System.Globalization.DateTimeStyles style = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function ParseExact (s As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), provider As IFormatProvider, Optional style As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

매개 변수

s
ReadOnlySpan<Char>

변환할 날짜 및 시간을 나타내는 문자를 포함하는 범위입니다.

format
ReadOnlySpan<Char>

s의 필수 형식을 정의하는 형식 지정자를 나타내는 문자를 포함하는 범위입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

style
DateTimeStyles

s, s에 나타날 수 있는 스타일 요소 또는 s에서 DateTime 값으로 변환하는 방법에 대한 추가 정보를 제공하는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 None입니다.

반환

DateTime

s, formatprovider에 지정된 내용에 따라 style에 포함된 날짜 및 시간에 해당하는 개체입니다.

적용 대상

ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)

지정된 형식 배열, 문화권별 형식 정보 및 스타일을 사용하여 지정된 날짜와 시간의 범위 표현을 해당하는 DateTime(으)로 변환합니다. 문자열 표현의 서식은 지정된 형식 중 최소한 하나와 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

public static DateTime ParseExact (ReadOnlySpan<char> s, string[] formats, IFormatProvider? provider, System.Globalization.DateTimeStyles style = System.Globalization.DateTimeStyles.None);
public static DateTime ParseExact (ReadOnlySpan<char> s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function ParseExact (s As ReadOnlySpan(Of Char), formats As String(), provider As IFormatProvider, Optional style As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

매개 변수

s
ReadOnlySpan<Char>

변환할 날짜 및 시간을 나타내는 문자를 포함하는 범위입니다.

formats
String[]

s에 허용되는 형식의 배열입니다.

provider
IFormatProvider

s에 대한 문화권별 서식 지정 정보를 제공하는 개체입니다.

style
DateTimeStyles

s에 사용할 수 있는 형식을 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 None입니다.

반환

DateTime

s, formatsprovider에 지정된 내용에 따라 style에 포함된 날짜 및 시간에 해당하는 개체입니다.

적용 대상

ParseExact(String, String, IFormatProvider, DateTimeStyles)

지정된 형식, 문화권별 형식 정보 및 스타일을 사용하여 날짜 및 시간의 지정된 문자열 표현을 해당 DateTime으로 변환합니다. 문자열 표현의 서식은 지정된 서식과 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

public:
 static DateTime ParseExact(System::String ^ s, System::String ^ format, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style);
public static DateTime ParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style);
public static DateTime ParseExact (string s, string format, IFormatProvider? provider, System.Globalization.DateTimeStyles style);
static member ParseExact : string * string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function ParseExact (s As String, format As String, provider As IFormatProvider, style As DateTimeStyles) As DateTime

매개 변수

s
String

날짜와 시간이 포함된 변환할 문자열입니다.

format
String

s의 필수 형식을 정의하는 서식 지정자입니다. 자세한 내용은 설명 섹션을 참조하세요.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

style
DateTimeStyles

s, s에 나타날 수 있는 스타일 요소 또는 s에서 DateTime 값으로 변환하는 방법에 대한 추가 정보를 제공하는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 None입니다.

반환

DateTime

s, formatprovider에 지정된 내용에 따라 style에 포함된 날짜 및 시간에 해당하는 개체입니다.

예외

s 또는 formatnull인 경우

s 또는 format가 빈 문자열입니다.

또는

sformat에 지정된 패턴과 일치하는 날짜 및 시간이 포함되어 있지 않습니다.

또는

s의 시간 구성 요소와 AM/PM 지정자가 일치하지 않습니다.

styleDateTimeStyles 값의 잘못된 조합이 포함되어 있습니다. 예를 들어 AssumeLocalAssumeUniversal이 포함되어 있습니다.

예제

다음 예제는 ParseExact(String, String, IFormatProvider) 메서드. 선행 공백은 허용되지 않으므로 매개 변수가 같 DateTimeStyles.None 으면 문자열 "5/01/2009 오전 8:30"을 성공적으로 styles 구문 분석할 수 format없습니다. 또한 "5/01/2009 09:00" 문자열은 필요에 따라 format "MM/dd/yyyyyhh:mm"로 구문 분석 format 할 수 없습니다. 날짜 문자열이 월 번호 앞에 선행 0이 없기 때문입니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo enUS = new CultureInfo("en-US");
      string dateString;
      DateTime dateValue;

      // Parse date with no style flags.
      dateString = " 5/01/2009 8:30 AM";
      try {
         dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      // Allow a leading space in the date string.
      try {
         dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }

      // Use custom formats with M and MM.
      dateString = "5/01/2009 09:00";
      try {
         dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      // Allow a leading space in the date string.
      try {
         dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }

      // Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00";
      try {
         dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      // Allow a leading space in the date string.
      try {
         dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS,
                                     DateTimeStyles.AdjustToUniversal);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }

      // Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z";
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                                     DateTimeStyles.None);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
      try {
         dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                                     DateTimeStyles.RoundtripKind);
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                           dateValue.Kind);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
      }
   }
}
// The example displays the following output:
//    ' 5/01/2009 8:30 AM' is not in an acceptable format.
//    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
//    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
//    '5/01/2009 09:00' is not in an acceptable format.
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    let enUS = CultureInfo "en-US"

    // Parse date with no style flags.
    let dateString = " 5/01/2009 8:30 AM"
    try
        let dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."
    
    // Allow a leading space in the date string.
    try
        let dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    // Use custom formats with M and MM.
    let dateString = "5/01/2009 09:00"
    try
        let dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    // Allow a leading space in the date string.
    try
        let dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    // Parse a string with time zone information.
    let dateString = "05/01/2009 01:30:42 PM -05:00"
    try
        let dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    // Allow a leading space in the date string.
    try
        let dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.AdjustToUniversal)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    // Parse a string representing UTC.
    let dateString = "2008-06-11T16:11:20.0904778Z"
    try
        let dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."

    try
        let dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)
        printfn $"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."
    with :? FormatException ->
        printfn $"'{dateString}' is not in an acceptable format."


// The example displays the following output:
//    ' 5/01/2009 8:30 AM' is not in an acceptable format.
//    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
//    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
//    '5/01/2009 09:00' is not in an acceptable format.
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim enUS As New CultureInfo("en-US") 
      Dim dateString As String
      Dim dateValue As Date
      
      ' Parse date with no style flags.
      dateString = " 5/01/2009 8:30 AM"
      Try
         dateValue = Date.ParseExact(dateString, "g", enUS, DateTimeStyles.None)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
      ' Allow a leading space in the date string.
      Try
         dateValue = Date.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
      
      ' Use custom formats with M and MM.
      dateString = "5/01/2009 09:00"
      Try
         dateValue = Date.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
      ' Allow a leading space in the date string.
      Try
         dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try

      ' Parse a string with time zone information.
      dateString = "05/01/2009 01:30:42 PM -05:00" 
      Try
         dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
      ' Allow a leading space in the date string.
      Try
         dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                                     DateTimeStyles.AdjustToUniversal)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
           
      ' Parse a string representing UTC.
      dateString = "2008-06-11T16:11:20.0904778Z"
      Try
         dateValue = Date.ParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                                     DateTimeStyles.None)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
      Try
         dateValue = Date.ParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                                     DateTimeStyles.RoundtripKind)
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End Try
   End Sub
End Module
' The example displays the following output:
'    ' 5/01/2009 8:30 AM' is not in an acceptable format.
'    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
'    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
'    '5/01/2009 09:00' is not in an acceptable format.
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).

설명

이 메서드는 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) 매개 변수로 정의된 형식이어야 하는 날짜의 문자열 표현을 format 구문 분석합니다. 또한 날짜 및 시간 요소가 s 지정한 format순서대로 나타나야 합니다. 매개 변수의 format 패턴과 일치하지 않는 경우 s 매개 변수에 정의된 style 변형이 있으면 메서드는 .을 throw합니다FormatException. 반면, 이 메서드는 DateTime.Parse(String, IFormatProvider, DateTimeStyles) 날짜의 문자열 표현을 형식 공급자의 DateTimeFormatInfo 개체에서 인식되는 형식 중 하나로 구문 분석합니다. 또한 이 DateTime.Parse(String, IFormatProvider, DateTimeStyles) 메서드를 사용하면 날짜 및 시간 요소가 s 임의의 순서로 표시되도록 할 수 있습니다.

매개 변수에 s 시간만 있고 날짜가 없는 경우 매개 변수에 플래그가 포함되지 DateTimeStyles.NoCurrentDateDefault 않는 한 style 현재 날짜가 사용됩니다. 이 경우 기본 날짜(DateTime.Date.MinValue)가 사용됩니다. 매개 변수에 s 날짜만 있고 시간이 없으면 자정(00:00:00)이 사용됩니다. 매개 변수는 style 매개 변수에 s 선행, 내부 또는 후행 공백 문자를 포함할 수 있는지 여부도 결정합니다.

표준 시간대 정보가 없는 경우 s 반환 DateTimeKind 개체의 속성은 .입니다DateTimeKind.Unspecified. 이 동작은 속성이 있는 값을 반환하는 플래그를 사용 DateTimeStyles.AssumeLocal 하거나 속성이 Kind DateTimeKind.Local있는 값을 Kind 반환 DateTime 하는 플래그 및 DateTimeStyles.AdjustToUniversal 플래그를 DateTime 사용하여 DateTimeStyles.AssumeUniversal 변경할 수 있습니다DateTimeKind.Utc. 표준 시간대 정보가 포함된 경우 s 시간이 필요한 경우 현지 시간으로 변환되고 Kind 반환 DateTime 된 개체의 속성은 .로 DateTimeKind.Local설정됩니다. 이 동작은 플래그를 DateTimeStyles.RoundtripKind 사용하여 UTC(협정 세계시)를 현지 시간으로 변환하지 않고 속성을 DateTimeKind.Utc로 설정 Kind 하여 변경할 수 있습니다.

매개 변수는 format 매개 변수의 s 필수 패턴을 정의합니다. 사용자 지정 날짜 및 시간 형식 문자열 테이블에서 하나 이상의 사용자 지정 형식 지정자 또는 표준 날짜 및 시간 형식 문자열 테이블에서 미리 정의된 패턴을 식별하는 단일 표준 형식 지정자로 구성됩니다.

사용자 지정 형식 패턴에서 날짜 또는 시간 구분 기호를 사용하지 않는 경우 매개 변수에 고정 문화 provider 권과 각 사용자 지정 형식 지정자의 가장 넓은 형식을 사용합니다. 예를 들어 패턴에서 시간을 지정하려는 경우 더 좁은 형식인 "H" 대신 더 넓은 형식인 "HH"를 지정합니다.

참고

구문 분석 작업이 성공하기 위해 단일 형식을 준수하도록 요구하는 s 대신 메서드를 DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 호출하고 허용되는 여러 형식을 지정할 수 있습니다. 이렇게 하면 구문 분석 작업이 성공할 가능성이 높아집니다.

매개 변수에는 styles 정의 format 되지 않은 공백이 표시 s 될 수 있는지 여부와 위치를 결정하고 구문 분석 작업의 정확한 동작을 제어하는 열거형의 하나 이상의 멤버 DateTimeStyles 가 포함됩니다. 다음 표에서는 열거형의 각 멤버가 DateTimeStyles 메서드 작업에 ParseExact(String, String, IFormatProvider, DateTimeStyles) 미치는 영향을 설명합니다.

DateTimeStyles 멤버 Description
AdjustToUniversal s 구문 분석하고 필요한 경우 UTC로 변환합니다. 표준 시간대 오프셋을 포함하거나 표준 시간대 정보가 styles 없지만 플래그를 DateTimeStyles.AssumeLocal 포함하는 경우 s s 메서드는 문자열을 구문 분석하고 반환된 DateTime 값을 UTC로 변환하기 위해 호출 ToUniversalTime 하고 속성을 DateTimeKind.Utc설정합니다Kind. UTC를 나타내거나 표준 시간대 정보를 styles 포함하지 않지만 플래그를 DateTimeStyles.AssumeUniversal 포함하는 경우 s s 메서드는 문자열을 구문 분석하고 반환된 DateTime 값에 대해 표준 시간대 변환을 수행하지 않으며 속성을 DateTimeKind.Utc설정합니다Kind. 다른 모든 경우에는 플래그가 적용되지 않습니다.
AllowInnerWhite 정의 format 되지 않은 공백이 개별 날짜 또는 시간 요소 사이에 표시될 수 있도록 지정합니다.
AllowLeadingWhite 정의 format 되지 않은 공백이 시작 부분에 s표시될 수 있도록 지정합니다.
AllowTrailingWhite 정의 format 되지 않은 공백이 .의 s끝에 표시될 수 있도록 지정합니다.
AllowWhiteSpaces 에 의해 format정의되지 않은 선행 공백, 내부 및 후행 공백을 포함할 수 있는 s 공백을 지정합니다.
AssumeLocal 표준 시간대 정보가 없는 경우 s 현지 시간을 나타내는 것으로 간주되도록 지정합니다. 플래그가 DateTimeStyles.AdjustToUniversal 없는 한 반환 DateTimeKind 값의 속성은 .로 DateTimeKind.Local설정됩니다.
AssumeUniversal 표준 시간대 정보가 없는 경우 s UTC를 나타내는 것으로 간주되도록 지정합니다. 플래그가 DateTimeStyles.AdjustToUniversal 없는 한 메서드는 반환 DateTime 된 값을 UTC에서 현지 시간으로 변환하고 해당 Kind 속성을 DateTimeKind.Local.로 설정합니다.
NoCurrentDateDefault 날짜 정보가 없는 시간이 포함된 경우 s 반환 값의 날짜는 .로 DateTime.MinValue.Date설정됩니다.
None s 매개 변수는 기본값을 사용하여 구문 분석됩니다. 있는 format 공백 이외의 공백은 허용되지 않습니다. 날짜 구성 요소가 없는 경우 s 반환 DateTime 된 값의 날짜는 0001년 1월 1일로 설정됩니다. 표준 시간대 정보가 없으면 s 반환 DateTimeKind 개체의 속성이 .로 DateTimeKind.Unspecified설정됩니다. 표준 시간대 정보가 있는 s경우 시간은 현지 시간으로 변환되고 Kind 반환 DateTime 된 개체의 속성은 .로 DateTimeKind.Local설정됩니다.
RoundtripKind 표준 시간대 정보를 포함하는 문자열의 경우 해당 속성이 .로 설정된 DateTimeKind.Local값 날짜 및 시간으로 Kind 변환 DateTime 하지 않도록 합니다. 이 플래그는 주로 UTC 시간을 현지 시간으로 변환하는 것을 방지합니다.

사용되는 s 특정 날짜 및 시간 기호 및 문자열(예: 특정 언어의 요일 이름)은 표준 형식 지정자 문자열인 경우 formats 정확한 형식과 마찬가지로 매개 변수에 의해 provider 정의됩니다. 매개 변수는 provider 다음 중 어느 것일 수 있습니다.

nullCultureInfo 경우 provider 현재 문화권에 해당하는 개체가 사용됩니다.

호출자 참고

.NET Framework 4 ParseExact 에서 메서드는 구문 분석할 문자열에 시간 구성 요소와 합의되지 않은 AM/PM 지정자가 포함된 경우를 throw FormatException 합니다. .NET Framework 3.5 이전 버전에서는 AM/PM 지정자가 무시됩니다.

추가 정보

적용 대상

ParseExact(String, String[], IFormatProvider, DateTimeStyles)

지정된 형식 배열, 문화권별 형식 정보 및 스타일을 사용하여 지정된 날짜와 시간의 문자열 표현을 해당 DateTime 표현으로 변환합니다. 문자열 표현의 서식은 지정된 형식 중 최소한 하나와 정확하게 일치해야 합니다. 그렇지 않으면 예외가 throw됩니다.

public:
 static DateTime ParseExact(System::String ^ s, cli::array <System::String ^> ^ formats, IFormatProvider ^ provider, System::Globalization::DateTimeStyles style);
public static DateTime ParseExact (string s, string[] formats, IFormatProvider provider, System.Globalization.DateTimeStyles style);
public static DateTime ParseExact (string s, string[] formats, IFormatProvider? provider, System.Globalization.DateTimeStyles style);
static member ParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function ParseExact (s As String, formats As String(), provider As IFormatProvider, style As DateTimeStyles) As DateTime

매개 변수

s
String

변환할 날짜 및 시간이 포함된 문자열입니다.

formats
String[]

s에 허용되는 형식의 배열입니다. 자세한 내용은 설명 섹션을 참조하세요.

provider
IFormatProvider

s에 대한 문화권별 서식 지정 정보를 제공하는 개체입니다.

style
DateTimeStyles

s에 사용할 수 있는 형식을 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 None입니다.

반환

DateTime

s, formatsprovider에 지정된 내용에 따라 style에 포함된 날짜 및 시간에 해당하는 개체입니다.

예외

s 또는 formatsnull인 경우

s이 빈 문자열인 경우

또는

formats의 요소가 빈 문자열입니다.

또는

sformats 요소에 해당하는 날짜 및 시간이 포함되어 있지 않습니다.

또는

s의 시간 구성 요소와 AM/PM 지정자가 일치하지 않습니다.

styleDateTimeStyles 값의 잘못된 조합이 포함되어 있습니다. 예를 들어 AssumeLocalAssumeUniversal이 포함되어 있습니다.

예제

다음 예제에서는 메서드를 DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 사용하여 가능한 여러 형식의 문자열을 성공적으로 구문 분석할 수 있는지 확인합니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
                         "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
                         "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
                         "M/d/yyyy h:mm", "M/d/yyyy h:mm",
                         "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                         "MM/d/yyyy HH:mm:ss.ffffff" };
      string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
                              "5/1/2009 6:32:00", "05/01/2009 06:32",
                              "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00",
                              "08/28/2015 16:17:39.125", "08/28/2015 16:17:39.125000" };
      DateTime dateValue;

      foreach (string dateString in dateStrings)
      {
         try {
            dateValue = DateTime.ParseExact(dateString, formats,
                                            new CultureInfo("en-US"),
                                            DateTimeStyles.None);
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
         }
         catch (FormatException) {
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
         }
      }
   }
}
// The example displays the following output:
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
//       Unable to convert '08/28/2015 16:17:39.125' to a date.
//       Converted '08/28/2015 16:17:39.125000' to 8/28/2015 4:17:39 PM.
open System
open System.Globalization

let formats = 
    [| "M/d/yyyy h:mm:ss tt"; "M/d/yyyy h:mm tt"
       "MM/dd/yyyy hh:mm:ss"; "M/d/yyyy h:mm:ss"
       "M/d/yyyy hh:mm tt"; "M/d/yyyy hh tt"
       "M/d/yyyy h:mm"; "M/d/yyyy h:mm"
       "MM/dd/yyyy hh:mm"; "M/dd/yyyy hh:mm"
       "MM/d/yyyy HH:mm:ss.ffffff" |]

let dateStrings = 
    [ "5/1/2009 6:32 PM"; "05/01/2009 6:32:05 PM"
      "5/1/2009 6:32:00"; "05/01/2009 06:32"
      "05/01/2009 06:32:00 PM"; "05/01/2009 06:32:00"
      "08/28/2015 16:17:39.125"; "08/28/2015 16:17:39.125000" ]

for dateString in dateStrings do
    try
        let dateValue = DateTime.ParseExact(dateString, formats, CultureInfo "en-US", DateTimeStyles.None)
        printfn $"Converted '{dateString}' to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}' to a date."

// The example displays the following output:
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
//       Unable to convert '08/28/2015 16:17:39.125' to a date.
//       Converted '08/28/2015 16:17:39.125000' to 8/28/2015 4:17:39 PM.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim formats() As String = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", _
                                 "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", _
                                 "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", _
                                 "M/d/yyyy h:mm", "M/d/yyyy h:mm", _
                                 "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                                 "MM/d/yyyy HH:mm:ss.ffffff" }
      Dim dateStrings() As String = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", _
                                     "5/1/2009 6:32:00", "05/01/2009 06:32", _
                                     "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00",
                                     "08/28/2015 16:17:39.125", "08/28/2015 16:17:39.125000" }

      Dim dateValue As DateTime
      
      For Each dateString As String In dateStrings
         Try
            dateValue = DateTime.ParseExact(dateString, formats, _
                                            New CultureInfo("en-US"), _
                                            DateTimeStyles.None)
            Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue)
         Catch e As FormatException
            Console.WriteLine("Unable to convert '{0}' to a date.", dateString)
         End Try                                               
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
'       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
'       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
'       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
'       Unable to convert '08/28/2015 16:17:39.125' to a date.
'       Converted '08/28/2015 16:17:39.125000' to 8/28/2015 4:17:39 PM.

설명

이 메서드는 DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 매개 변수에 할당된 패턴 중 하나와 일치하는 날짜의 문자열 표현을 formats 구문 분석합니다. 문자열 s 이 매개 변수로 정의된 styles 변형 중 하나와 이러한 패턴 중 하나와 일치하지 않으면 메서드가 throw FormatException됩니다. 단일 서식 패턴이 아닌 여러 서식 패턴과 비교 s 하는 것 외에도 이 오버로드는 메서드와 동일하게 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) 동작합니다.

매개 변수에는 s 구문 분석할 날짜와 시간이 포함됩니다. 매개 변수에 s 시간 및 날짜만 포함된 경우 매개 변수에 플래그가 포함되지 DateTimeStyles.NoCurrentDateDefault 않는 한 style 현재 날짜가 사용됩니다. 이 경우 기본 날짜(DateTime.Date.MinValue)가 사용됩니다. 매개 변수에 s 날짜만 있고 시간이 없는 경우 자정(00:00:00)이 사용됩니다. 또한 매개 변수는 style 매개 변수에 s 형식 문자열 중 하나에서 허용하는 공백 이외의 선행, 내부 또는 후행 공백 문자를 포함할 수 있는지 여부를 결정합니다 formats.

표준 시간대 정보가 없는 경우 s 반환 DateTimeKind 개체의 속성은 .입니다DateTimeKind.Unspecified. 이 동작은 속성이 있는 값을 반환하는 플래그를 사용 DateTimeStyles.AssumeLocal 하거나 속성DateTimeKind.LocalKind 있는 값을 Kind 반환하는 플래그 및 DateTimeStyles.AdjustToUniversal 플래그를 DateTime 사용하여 DateTimeStyles.AssumeUniversal 변경할 수 있습니다DateTimeKind.Utc.DateTime 표준 시간대 정보가 포함된 경우 s 시간이 필요한 경우 현지 시간으로 변환되고 Kind 반환 DateTime 된 개체의 속성이 로 설정 DateTimeKind.Local됩니다. 이 동작은 플래그를 사용하여 DateTimeStyles.RoundtripKind UTC(협정 세계시)를 현지 시간으로 변환하지 않고 속성을 DateTimeKind.Utc로 설정 Kind 하여 변경할 수 있습니다.

매개 변수에는 formats 패턴 배열이 포함되어 있으며, 그 s 중 하나는 구문 분석 작업이 성공하는 경우 정확히 일치해야 합니다. 매개 변수의 formats 패턴은 사용자 지정 날짜 및 시간 형식 문자열 테이블에서 하나 이상의 사용자 지정 서식 지정자 또는 표준 날짜 및 시간 형식 문자열 테이블에서 미리 정의된 패턴을 식별하는 단일 표준 형식 지정자로 구성됩니다.

사용자 지정 서식 패턴에서 날짜 또는 시간 구분 기호를 사용하지 않는 경우 매개 변수의 고정 문화권 provider 과 각 사용자 지정 형식 지정자의 가장 넓은 형식을 사용합니다. 예를 들어 패턴에서 시간을 지정하려면 더 좁은 형식인 "H" 대신 더 넓은 형식인 "HH"를 지정합니다.

매개 변수에는 styles 정의되지 않은 format 공백이 표시 s 될 수 있는지 여부와 위치를 결정하고 구문 분석 작업의 정확한 동작을 제어하는 열거형의 하나 이상의 멤버 DateTimeStyles 가 포함됩니다. 다음 표에서는 열거형의 각 멤버가 DateTimeStyles 메서드 작업에 ParseExact(String, String, IFormatProvider, DateTimeStyles) 미치는 영향을 설명합니다.

DateTimeStyles 멤버 Description
AdjustToUniversal s 구문 분석하고 필요한 경우 UTC로 변환합니다. 표준 시간대 오프셋을 포함하거나 표준 시간대 정보가 styles 없지만 플래그를 DateTimeStyles.AssumeLocal 포함하는 경우 s s 메서드는 문자열을 구문 분석하고 반환된 DateTime 값을 UTC로 변환하기 위해 호출 ToUniversalTime 하고 Kind 속성을 DateTimeKind.Utc설정합니다. s UTC를 나타내거나 표준 시간대 정보를 포함하지 않지만 styles 플래그를 DateTimeStyles.AssumeUniversal 포함하는 경우 s 메서드는 문자열을 구문 분석하고 반환된 DateTime 값에 대해 표준 시간대 변환을 수행하지 않고 속성을 KindDateTimeKind.Utc로 설정합니다. 다른 모든 경우에서는 플래그가 적용되지 않습니다.
AllowInnerWhite 정의 format 되지 않은 공백이 개별 날짜 또는 시간 요소 사이에 나타날 수 있도록 지정합니다.
AllowLeadingWhite 정의 format 되지 않은 공백이 시작 부분에 s표시되도록 지정합니다.
AllowTrailingWhite 정의 format 되지 않은 공백이 끝에 s표시될 수 있도록 지정합니다.
AllowWhiteSpaces s 에 의해 format정의되지 않은 선행 공백, 내부 및 후행 공백을 포함할 수 있는 공백을 지정합니다.
AssumeLocal 표준 시간대 정보가 없는 경우 s 현지 시간을 나타내는 것으로 간주되도록 지정합니다. 플래그가 DateTimeStyles.AdjustToUniversal 없는 한 반환 DateTimeKind 값의 속성은 .로 DateTimeKind.Local설정됩니다.
AssumeUniversal 표준 시간대 정보가 없는 경우 s UTC를 나타내는 것으로 간주되도록 지정합니다. 플래그가 DateTimeStyles.AdjustToUniversal 없는 한 메서드는 반환 DateTime 된 값을 UTC에서 현지 시간으로 변환하고 해당 Kind 속성을 DateTimeKind.Local.로 설정합니다.
NoCurrentDateDefault 날짜 정보가 없는 시간이 포함된 경우 s 반환 값의 날짜는 .로 DateTime.MinValue.Date설정됩니다.
None s 매개 변수는 기본값을 사용하여 구문 분석됩니다. 있는 format 공백 이외의 공백은 허용되지 않습니다. 날짜 구성 요소가 없는 경우 s 반환 DateTime 된 값의 날짜는 0001년 1월 1일로 설정됩니다. 표준 시간대 정보가 없으면 s 반환 DateTimeKind 개체의 속성이 .로 DateTimeKind.Unspecified설정됩니다. 표준 시간대 정보가 있는 s경우 시간은 현지 시간으로 변환되고 Kind 반환 DateTime 된 개체의 속성은 로 DateTimeKind.Local설정됩니다.
RoundtripKind 표준 시간대 정보를 포함하는 문자열의 경우 해당 속성이 설정된 날짜 및 시간으로의 변환을 Kind 방지하려고 합니다 DateTimeKind.Local. 이 플래그는 주로 UTC 시간을 현지 시간으로 변환하는 것을 방지합니다.

사용되는 특정 날짜 및 시간 기호 및 문자열(예: 특정 언어의 요일 이름)s은 표준 형식 지정자 문자열인 경우 formats 정확한 형식과 마찬가지로 매개 변수에 의해 provider 정의됩니다. 매개 변수는 provider 다음 중 어느 것일 수 있습니다.

nullCultureInfo 경우 provider 현재 문화권에 해당하는 개체가 사용됩니다.

호출자 참고

.NET Framework 4 ParseExact 에서는 구문 분석할 문자열에 시간 구성 요소와 규약이 없는 AM/PM 지정자가 포함된 경우 메서드가 throw FormatException 됩니다. .NET Framework 3.5 이전 버전에서는 AM/PM 지정자가 무시됩니다.

추가 정보

적용 대상