다음을 통해 공유


DateTime.Parse 메서드

정의

날짜 및 시간의 문자열 표현을 해당하는 값으로 DateTime 변환합니다.

오버로드

Name Description
Parse(String)

현재 문화권의 규칙을 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 값으로 변환합니다.

Parse(ReadOnlySpan<Char>, IFormatProvider)

문자 범위를 값으로 구문 분석합니다.

Parse(String, IFormatProvider)

문화권별 형식 정보를 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 형식으로 변환합니다.

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

문화권별 형식 정보 및 서식 스타일을 사용하여 날짜 및 시간의 DateTime 문자열 표현이 포함된 메모리 범위를 해당 값으로 변환합니다.

Parse(String, IFormatProvider, DateTimeStyles)

문화권별 서식 정보와 서식 스타일을 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 형식으로 변환합니다.

예제

메서드를 호출 DateTime.Parse 하는 수많은 예제는 이 문서의 설명 서 섹션 전체와 개별 DateTime.Parse 오버로드에 대한 설명서에 산재되어 있습니다.

C#용 DateTime.Parse.NET Core 프로젝트에 포함된 전체 예제 집합을 다운로드할 수도 있습니다.

설명

이 섹션에서는 다음을 수행합니다.

어떤 메서드를 호출합니까?

받는 사람 외침
현재 문화권의 규칙을 사용하여 날짜 및 시간 문자열을 구문 분석합니다. Parse(String) 과부하
특정 문화권의 규칙을 사용하여 날짜 및 시간 문자열을 구문 분석합니다. Parse(String, IFormatProvider) 오버로드( 구문 분석 및 문화권 규칙 참조)
특수 스타일 요소(예: 공백 또는 공백 없음)를 사용하여 날짜 및 시간 문자열을 구문 분석합니다. Parse(String, IFormatProvider, DateTimeStyles) 과부하
특정 형식이어야 하는 날짜 및 시간 문자열을 구문 분석합니다. DateTime.ParseExact 또는 DateTime.TryParseExact
날짜 및 시간 문자열을 구문 분석하고 UTC 또는 현지 시간으로 변환을 수행합니다. Parse(String, IFormatProvider, DateTimeStyles) 과부하
예외를 처리하지 않고 날짜 및 시간 문자열을 구문 분석합니다. DateTime.TryParse 메서드
서식 지정 작업으로 만든 날짜 및 시간 값을 복원(왕복)합니다. "o" 또는 "r" 표준 형식 문자열을 메서드에 ToString(String) 전달하고 다음을 사용하여 오버로드를 Parse(String, IFormatProvider, DateTimeStyles) 호출합니다. DateTimeStyles.RoundtripKind
날짜 및 시간 문자열을 컴퓨터(및 문화권) 경계를 넘어 고정된 형식으로 구문 분석합니다. DateTime.ParseExact 또는 DateTime.TryParseExact 메서드

구문 분석할 문자열입니다.

메서드는 Parse 날짜 및 시간 값의 문자열 표현을 해당 값으로 DateTime 변환하려고 합니다. 예외를 throw FormatException 하지 않고 입력 문자열을 완전히 구문 분석하려고 합니다. 개체를 허용하는 오버로드를 IFormatProvider 사용하는 경우 구문 분석 StringToParse하는 데 사용됩니다. 이러한 개체가 제공되지 CurrentCulture 않으면 대신 사용됩니다.

중요하다

인식할 수 없는 문자열 형식으로 인해 구문 분석 작업이 실패하면 메서드가 Parse throw FormatException되는 반면 메서드는 TryParse 반환합니다 false. 예외 처리 비용이 많이 들 수 있으므로 입력 원본을 신뢰할 수 있기 때문에 구문 분석 작업이 성공할 것으로 예상되는 경우에 사용해야 Parse 합니다. TryParse 는 구문 분석 오류가 발생할 가능성이 높거나, 특히 입력 원본이 신뢰할 수 없거나 성공적으로 구문 분석되지 않는 문자열을 대체할 적절한 기본값이 있기 때문에 바람직합니다.

구문 분석할 문자열은 다음 형식을 사용할 수 있습니다.

  • 날짜 및 시간 구성 요소가 있는 문자열입니다.

  • 날짜가 있지만 시간 구성 요소가 없는 문자열입니다. 시간 구성 요소가 없는 경우 메서드는 자정 12:00을 가정합니다. 날짜 구성 요소에 두 자리 연도가 있는 경우 현재 문화권의 현재 달력 또는 지정된 문화권의 현재 달력을 기준으로 Calendar.TwoDigitYearMax 1년으로 변환됩니다(null provider 이 아닌 인수와 오버로드를 사용하는 경우).

  • 월 및 연도만 포함하지만 일 구성 요소가 없는 날짜 구성 요소가 있는 문자열입니다. 메서드는 해당 월의 첫 번째 날을 가정합니다.

  • 월과 일만 포함하지만 연도 구성 요소가 없는 날짜 구성 요소가 있는 문자열입니다. 메서드는 현재 연도를 가정합니다.

  • 시간이 있지만 날짜 구성 요소가 없는 문자열입니다. 이 메서드는 오버로드를 호출 Parse(String, IFormatProvider, DateTimeStyles) 하고 인수에 styles 포함하지 DateTimeStyles.NoCurrentDateDefault 않는 한 현재 날짜를 가정합니다. 이 경우 메서드는 0001년 1월 1일을 가정합니다.

  • 날짜 구성 요소가 없는 시간 및 AM/PM 지정자만 포함하는 시간 구성 요소가 있는 문자열입니다. 메서드는 현재 날짜와 분 및 초가 없는 시간을 가정합니다. 오버로드를 호출 Parse(String, IFormatProvider, DateTimeStyles) 하여 이 동작을 변경할 수 있으며 인수에 styles 포함 DateTimeStyles.NoCurrentDateDefault 할 수 있습니다. 이 경우 메서드는 0001년 1월 1일로 가정합니다.

  • 표준 시간대 정보를 포함하고 ISO 8601을 준수하는 문자열입니다. 다음 예제에서 첫 번째 문자열은 UTC(협정 세계시)를 지정하고, 두 번째 문자열은 UTC보다 7시간 이전인 표준 시간대의 시간을 지정합니다.

    "2008-11-01T19:35:00.0000000Z" "2008-11-01T19:35:00.00000000-07:00"

  • GMT 지정자를 포함하고 RFC 1123 시간 형식을 준수하는 문자열입니다. 예를 들어:

    "토, 01 11 월 2008 19:35:00 GMT"

  • 표준 시간대 오프셋 정보와 함께 날짜 및 시간을 포함하는 문자열입니다. 예를 들어:

    "03/01/2009 05:42:00 -5:00"

다음 예제에서는 현재 문화권의 서식 규칙을 사용하여 이러한 각 형식의 문자열을 구문 분석합니다. 이 경우 en-US 문화권입니다.

using System;

public class Example
{
   public static void Main()
   {
      (string dateAsString, string description)[]  dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"),
                                                                ("08/18/2018", "String with a date component only"),
                                                                ("8/2018", "String with a month and year component only"),
                                                                ("8/18", "String with a month and day component only"),
                                                                ("07:22:16", "String with a time component only"),
                                                                ("7 PM", "String with an hour and AM/PM designator only"),
                                                                ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),
                                                                ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                                                                ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                                                                ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) };

      Console.WriteLine($"Today is {DateTime.Now:d}\n");

      foreach (var item in dateInfo) {
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}");
      }
   }
}
// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
module Parse6

open System

let  dateInfo = 
    [ "08/18/2018 07:22:16", "String with a date and time component"
      "08/18/2018", "String with a date component only"
      "8/2018", "String with a month and year component only"
      "8/18", "String with a month and day component only"
      "07:22:16", "String with a time component only"
      "7 PM", "String with an hour and AM/PM designator only"
      "2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"
      "2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"
      "Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"
      "08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ]

printfn $"Today is {DateTime.Now:d}\n"

for dateAsString, description in dateInfo do
    printfn $"""{description + ":",-52} '{dateAsString}' --> {DateTime.Parse(dateAsString)}"""


// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

Public Module Strings
   Public Sub Main()
      Dim dateInfo() As (dateAsString As String, description As String) = 
                     { ("08/18/2018 07:22:16", "String with a date and time component"),
                       ("08/18/2018", "String with a date component only"),
                       ("8/2018", "String with a month and year component only"),
                       ("8/18", "String with a month and day component only"),
                       ("07:22:16", "String with a time component only"),
                       ("7 PM", "String with an hour and AM/PM designator only"),
                       ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),   
                       ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                       ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                       ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }
   
      Console.WriteLine($"Today is {Date.Now:d}{vbCrLf}")
      
      For Each item in dateInfo
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}")        
      Next
   End Sub
End Module
' The example displays output like the following:
'   Today is 2/22/2018
'   
'   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
'   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
'   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
'   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
'   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
'   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
'   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
'   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
'   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
'   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

입력 문자열이 구문 분석 메서드에서 사용하는 달력에서 윤년의 윤일을 나타내는 경우( 구문 분석 및 문화권 규칙 참조) Parse 메서드는 문자열을 성공적으로 구문 분석합니다. 입력 문자열이 윤년이 아닌 연도의 윤일을 나타내는 경우 메서드는 을 throw합니다 FormatException.

메서드는 Parse 현재 또는 지정된 문화권의 서식 규칙을 사용하여 날짜 및 시간의 문자열 표현을 구문 분석하려고 하기 때문에 여러 문화권에서 문자열을 구문 분석하려고 하면 실패할 수 있습니다. 다른 로캘에서 특정 날짜 및 시간 형식을 구문 분석하려면 메서드의 DateTime.ParseExact 오버로드 중 하나를 사용하고 형식 지정자를 제공합니다.

구문 분석 및 문화 규칙

구문 분석할 문자열(다음 표에 표시 s 됨)이 ISO 8601 패턴을 따르지 않는 한 메서드의 모든 오버로드는 Parse 문화권을 구분합니다. 구문 분석 작업은 다음과 같이 파생된 개체의 DateTimeFormatInfo 서식 지정 정보를 사용합니다.

중요하다

일본 달력의 시대는 황제의 통치를 기반으로하므로 변경 될 것으로 예상된다. 예를 들어, 2019년 5월 1일은 JapaneseCalendarJapaneseLunisolarCalendar에서 레이와 시대의 시작을 알렸다. 이러한 시대의 변화는 이러한 달력을 사용하는 모든 애플리케이션에 영향을 줍니다. 자세한 내용과 애플리케이션이 영향을 받는지 여부를 확인하려면 .NET의 일본 달력에서 새 시대 처리를 참조하세요. Windows 시스템에서 애플리케이션을 테스트하여 시대 변화에 대한 준비 상태를 확인하는 방법에 대한 자세한 내용은 일본 시대 변경을 위한 애플리케이션 준비를 참조하세요. 여러 연대가 있는 달력을 지원하는 .NET의 기능과 여러 연대를 지원하는 달력으로 작업할 때 모범 사례는 연대 작업(Working with era)을 참조하세요.

전화하는 경우 그리고 provider 서식 지정 정보는
Parse(String) - 현재 문화권(DateTimeFormatInfo.CurrentInfo 속성)
Parse(String, IFormatProvider) 또는 Parse(String, IFormatProvider, DateTimeStyles) DateTimeFormatInfo 개체 지정한 DateTimeFormatInfo 개체입니다.
Parse(String, IFormatProvider) 또는 Parse(String, IFormatProvider, DateTimeStyles) null 현재 문화권(DateTimeFormatInfo.CurrentInfo 속성)
Parse(String, IFormatProvider) 또는 Parse(String, IFormatProvider, DateTimeStyles) CultureInfo 개체 CultureInfo.DateTimeFormat 속성
Parse(String, IFormatProvider) 또는 Parse(String, IFormatProvider, DateTimeStyles) 사용자 지정 IFormatProvider 구현 IFormatProvider.GetFormat 메서드

개체 DateTimeFormatInfo.Calendar 에서 DateTimeFormatInfo 서식 지정 정보를 파생할 때 속성은 구문 분석 작업에 사용되는 달력을 정의합니다.

표준 문화권과 다른 사용자 지정 설정이 있는 개체를 사용하여 날짜 및 시간 문자열을 구문 분석하는 경우 메서드 대신 Parse 메서드를 사용하여 DateTimeFormatInfoParseExact 변환에 성공할 가능성을 높입니다. 비표준 날짜 및 시간 문자열은 복잡하고 구문 분석하기 어려울 수 있습니다. 이 메서드는 Parse 여러 암시적 구문 분석 패턴으로 문자열을 구문 분석하려고 시도하며 모두 실패할 수 있습니다. 반면, 메서드를 ParseExact 사용하려면 성공할 가능성이 있는 하나 이상의 정확한 구문 분석 패턴을 명시적으로 지정해야 합니다. 자세한 내용은 항목의 "DateTimeFormatInfo 및 동적 데이터" 섹션을 DateTimeFormatInfo 참조하세요.

중요하다

특정 문화권에 대한 서식 지정 규칙은 동적이며 변경될 수 있습니다. 즉, 기본(현재) 문화권의 서식 규칙에 따라 달라지거나 고정 문화권 이외의 문화권을 나타내는 개체를 지정 IFormatProvider 하는 구문 분석 작업은 다음 중 한 가지가 발생하는 경우 예기치 않게 실패할 수 있습니다.

  • 문화권별 데이터는 .NET Framework의 주 버전 또는 부 버전 간에 또는 기존 버전의 .NET Framework 업데이트로 인해 변경되었습니다.
  • 문화권별 데이터는 사용자 기본 설정을 반영하며, 머신마다, 세션마다 다를 수 있습니다.
  • 문화권별 데이터는 표준 문화권 또는 사용자 지정 문화권의 설정을 재정의하는 대체 문화권을 나타냅니다.

문화권 데이터의 변경 내용과 관련된 데이터 및 시간 문자열을 구문 분석하는 데 어려움을 방지하기 위해 고정 문화권을 사용하여 날짜 및 시간 문자열을 구문 분석하거나 또는 TryParseExact 메서드를 호출 ParseExact 하고 구문 분석할 문자열의 정확한 형식을 지정할 수 있습니다. 날짜 및 시간 데이터를 직렬화 및 역직렬화하는 경우 고정 문화권의 서식 규칙을 사용하거나 이진 형식으로 값을 직렬화하고 역직렬화할 DateTime 수 있습니다.

자세한 내용은 항목의 "동적 문화권 데이터" 섹션 CultureInfo 및 항목의 "DateTime 값 유지" 섹션을 DateTime 참조하세요.

구문 분석 및 스타일 요소

모든 Parse 오버로드는 입력 문자열의 선행, 내부 또는 후행 공백 문자를 무시합니다(다음 표에 표시됨 s ). 날짜 및 시간은 선행 및 후행 NUMBER SIGN 문자 쌍("#", U+0023)으로 괄호로 묶을 수 있으며 하나 이상의 NULL 문자(U+0000)로 후행할 수 있습니다.

또한 오버로드에는 Parse(String, IFormatProvider, DateTimeStyles)styles 열거형의 하나 이상의 멤버로 구성된 매개 변수가 DateTimeStyles 있습니다. 이 매개 변수는 s 해석 방법 및 구문 분석 작업을 날짜 및 시간으로 변환 s 하는 방법을 정의합니다. 다음 표에서는 각 DateTimeStyles 멤버가 구문 분석 작업에 미치는 영향을 설명합니다.

DateTimeStyles 멤버 변환에 미치는 영향
AdjustToUniversal s 구문 분석하고 필요한 경우 다음과 같이 UTC로 변환합니다.

- 표준 시간대 오프셋을 포함하거나 표준 시간대 정보가 styles 없지만 플래그를 AssumeLocal 포함하는 경우 ss 메서드는 문자열을 구문 분석하고 반환된 DateTime 값을 UTC로 변환하기 위해 호출 ToUniversalTime 하고 속성을 DateTimeKind.Utc설정합니다Kind.
- UTC를 나타내거나 표준 시간대 정보를 포함하지 않지만 플래그를 포함하는 경우 ss 메서드는 문자열을 구문 분석하고 반환된 DateTime 값에 대해 표준 시간대 변환을 수행하지 않고 속성을 DateTimeKind.Utc설정합니다Kind.AssumeUniversalstyles
- 다른 모든 경우에서는 플래그가 적용되지 않습니다.
AllowInnerWhite 이 값은 무시됩니다. 내부 공백은 항상 의 날짜 및 시간 요소 s에서 허용됩니다.
AllowLeadingWhite 이 값은 무시됩니다. 선행 공백은 항상 의 날짜 및 시간 요소 s에서 허용됩니다.
AllowTrailingWhite 이 값은 무시됩니다. 후행 공백은 항상 의 날짜 및 시간 요소 s에서 허용됩니다.
AllowWhiteSpaces s에 선행, 내부 및 후행 공백이 포함될 수 있음을 명시합니다. 이것이 기본 동작입니다. 와 같은 DateTimeStyles보다 제한적인 None 열거형 값을 제공하여 재정의할 수 없습니다.
AssumeLocal 표준 시간대 정보가 없는 경우 s 현지 시간으로 간주되도록 지정합니다. AdjustToUniversal 플래그가 존재하지 않는 경우 반환된 Kind 값의 DateTime 속성은 DateTimeKind.Local으로 설정됩니다.
AssumeUniversal 표준 시간대 정보가 없는 경우 s UTC가 가정되도록 지정합니다. 플래그가 AdjustToUniversal 없는 한 메서드는 반환 DateTime 된 값을 UTC에서 현지 시간으로 변환하고 해당 Kind 속성을 DateTimeKind.Local.로 설정합니다.
None 유효하지만 이 값은 무시됩니다.
RoundtripKind 표준 시간대 정보를 포함하는 문자열의 경우 날짜 및 시간 문자열 DateTime 을 해당 속성이 설정된 현지 시간을 나타내는 값으로 Kind 변환하지 않도록 합니다 DateTimeKind.Local. 일반적으로 이러한 문자열은 메서드를 DateTime.ToString(String) 호출하고 "o", "r" 또는 "u" 표준 형식 지정자를 사용하여 생성됩니다.

반환 값 및 DateTime.Kind

DateTime.Parse 오버로드는 속성에 DateTime 표준 시간대 정보가 포함된 값을 Kind 반환합니다. 시간이 다음과 임을 나타낼 수 있습니다.

일반적으로 메서드는 Parse 속성이 .인 개체를 DateTime 반환합니다DateTimeKind.UnspecifiedKind. 그러나 메서드는 Parse 표준 시간대 변환을 수행하고 값 및 매개 변수에 따라 속성 값을 Kindsstyles 다르게 설정할 수도 있습니다.

표준 시간대 변환 Kind 속성
s 에는 표준 시간대 정보가 포함되어 있습니다. 날짜와 시간은 현지 표준 시간대의 시간으로 변환됩니다. DateTimeKind.Local
s 에는 표준 시간대 정보가 포함되고 styles 플래그가 AdjustToUniversal 포함됩니다. 날짜와 시간은 UTC(협정 세계시)로 변환됩니다. DateTimeKind.Utc
s 는 Z 또는 GMT 표준 시간대 지정자를 styles 포함하고 플래그를 RoundtripKind 포함합니다. 날짜와 시간은 UTC로 해석됩니다. DateTimeKind.Utc

다음 예제에서는 표준 시간대 정보가 포함된 날짜 문자열을 현지 표준 시간대의 시간으로 변환합니다.

using System;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = {"2008-05-01T07:34:42-5:00",
                              "2008-05-01 7:34:42Z",
                              "Thu, 01 May 2008 07:34:42 GMT"};
      foreach (string dateString in dateStrings)
      {
         DateTime convertedDate = DateTime.Parse(dateString);
         Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
      }
   }
}
// These calls to the DateTime.Parse method display the following output:
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
open System

let dateStrings = 
    [ "2008-05-01T07:34:42-5:00"
      "2008-05-01 7:34:42Z"
      "Thu, 01 May 2008 07:34:42 GMT" ]

for dateString in dateStrings do
    let convertedDate = DateTime.Parse dateString
    printfn $"Converted {dateString} to {convertedDate.Kind} time {convertedDate}"

// These calls to the DateTime.Parse method display the following output:
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Module Example
   Public Sub Main()
      Dim dateStrings() As String = {"2008-05-01T07:34:42-5:00", 
                                     "2008-05-01 7:34:42Z", 
                                     "Thu, 01 May 2008 07:34:42 GMT"}
      
      For Each dateStr In dateStrings
         Dim convertedDate As Date = Date.Parse(dateStr)
         Console.WriteLine($"Converted {dateStr} to {convertedDate.Kind} time {convertedDate}")
      Next 
   End Sub
End Module
' These calls to the DateTime.Parse method display the following output:
'   Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
'   Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
'   Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM

플래그를 사용하여 DateTimeStyles.RoundtripKind 서식 지정 및 구문 분석 작업 중에 날짜 및 시간 속성 값을 Kind 유지할 수도 있습니다. 다음 예제에서는 플래그가 "o", "r" 또는 "u" 형식 지정자를 사용하여 문자열로 변환되는 값에 대한 DateTime 구문 분석 작업에 미치는 영향을 보여 RoundtripKind 줍니다.

   string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00",
                               "2008-09-15T09:30:41.7752486Z",
                               "2008-09-15T09:30:41.7752486",
                               "2008-09-15T09:30:41.7752486-04:00",
                               "Mon, 15 Sep 2008 09:30:41 GMT" };
   foreach (string formattedDate in formattedDates)
   {
      Console.WriteLine(formattedDate);
      DateTime roundtripDate = DateTime.Parse(formattedDate, null,
                                              DateTimeStyles.RoundtripKind);
      Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.");

      DateTime noRoundtripDate = DateTime.Parse(formattedDate, null,
                                                DateTimeStyles.None);
      Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.");
   }
// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
let formattedDates = 
    [ "2008-09-15T09:30:41.7752486-07:00"
      "2008-09-15T09:30:41.7752486Z"
      "2008-09-15T09:30:41.7752486"
      "2008-09-15T09:30:41.7752486-04:00"
      "Mon, 15 Sep 2008 09:30:41 GMT" ]

for formattedDate in formattedDates do
    printfn $"{formattedDate}"
    let roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind)
    printfn $"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time."

    let noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None)
    printfn $"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time."

// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
Dim formattedDates() = { "2008-09-15T09:30:41.7752486-07:00", 
                           "2008-09-15T09:30:41.7752486Z",  
                           "2008-09-15T09:30:41.7752486",  
                           "2008-09-15T09:30:41.7752486-04:00", 
                           "Mon, 15 Sep 2008 09:30:41 GMT" }
For Each formattedDate In formattedDates
   Console.WriteLine(formattedDate)
   Dim roundtripDate = DateTime.Parse(formattedDate, Nothing,  
                                      DateTimeStyles.RoundtripKind)                        
   Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.")                                          
   Dim noRoundtripDate = DateTime.Parse(formattedDate, Nothing,                                                                                                  DateTimeStyles.None)
   Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.")
Next         
' The example displays the following output:
'       2008-09-15T09:30:41.7752486-07:00
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486Z
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'       2008-09-15T09:30:41.7752486-04:00
'          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'       Mon, 15 Sep 2008 09:30:41 GMT
'          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.

Parse(String)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

현재 문화권의 규칙을 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 값으로 변환합니다.

public:
 static DateTime Parse(System::String ^ s);
public static DateTime Parse(string s);
static member Parse : string -> DateTime
Public Shared Function Parse (s As String) As DateTime

매개 변수

s
String

변환할 날짜 및 시간이 들어 있는 문자열입니다. 자세한 내용은 구문 분석할 문자열 을 참조하세요.

반환

에 포함된 s날짜 및 시간과 동일한 개체입니다.

예외

snull입니다.

s 는 날짜 및 시간의 유효한 문자열 표현을 포함하지 않습니다.

예제

다음 예제에서는 여러 날짜 및 시간 값의 문자열 표현을 구문 분석합니다.

  • 예제 출력을 생성하는 데 사용되는 컴퓨터의 현재 문화권에 대한 서식 규칙을 제공하는 기본 형식 공급자를 사용합니다. 이 예제의 출력은 en-US 문화권의 서식 규칙을 반영합니다.

  • 기본 스타일 값(예 AllowWhiteSpaces: .)을 사용합니다.

메서드가 다른 문화권의 서식 지정 규칙을 사용하여 날짜 및 시간의 문자열 표현을 구문 분석하려고 할 때 throw되는 예외를 처리 FormatException 합니다. 또한 현재 문화권의 서식 규칙을 사용하지 않는 날짜 및 시간 값을 성공적으로 구문 분석하는 방법도 보여 줍니다.

using System;
using System.Globalization;

public class DateTimeParser
{
   public static void Main()
   {
      // Assume the current culture is en-US.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      // Use standard en-US date and time value
      DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Reverse month and day to conform to the fr-FR culture.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Call another overload of Parse to successfully convert string
      // formatted according to conventions of fr-FR culture.
      try {
         dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Parse string with date but no time component.
      dateString = "2/16/2008";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }
   }
}
// The example displays the following output to the console:
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
//       Unable to convert '16/02/2008 12:15:12'.
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Assume the current culture is en-US.
    // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

    // Use standard en-US date and time value
    let dateString = "2/16/2008 12:15:12 PM"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Reverse month and day to conform to the fr-FR culture.
    // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
    let dateString = "16/02/2008 12:15:12"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        Console.WriteLine("Unable to convert '{0}'.", dateString)

    // Call another overload of Parse to successfully convert string
    // formatted according to conventions of fr-FR culture.
    try
        let dateValue = DateTime.Parse(dateString, CultureInfo("fr-FR", false))
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Parse string with date but no time component.
    let dateString = "2/16/2008"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    0

// The example displays the following output to the console:
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
//       Unable to convert '16/02/2008 12:15:12'.
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Imports System.Globalization

Class DateTimeParser
   Public Shared Sub Main()
      ' Assume the current culture is en-US. 
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.

      ' Use standard en-US date and time value
      Dim dateValue As Date
      Dim dateString As String = "2/16/2008 12:15:12 PM"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
            
      ' Reverse month and day to conform to the fr-FR culture.
      ' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' Call another overload of Parse to successfully convert string
      ' formatted according to conventions of fr-FR culture.      
      Try
         dateValue = Date.Parse(dateString, New CultureInfo("fr-FR", False))
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
      
      ' Parse string with date but no time component.
      dateString = "2/16/2008"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
   End Sub 
End Class 
' The example displays the following output to the console:
'       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
'       Unable to convert '16/02/2008 12:15:12'.
'       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
'       '2/16/2008' converted to 2/16/2008 12:00:00 AM.

설명

표준 시간대 정보가 포함된 경우 s 이 메서드는 DateTimeKind.Local 속성이 있는 Kind 값을 반환 DateTime 하고 날짜와 시간을 현지 시간으로 s 변환합니다. 그렇지 않으면 표준 시간대 변환을 수행하지 않고 속성DateTimeKind.UnspecifiedKind 있는 DateTime 값을 반환합니다.

이 오버로드는 현재 문화권 s 의 서식 규칙을 사용하여 구문 분석을 시도합니다. 현재 문화권은 속성으로 CurrentCulture 표시됩니다. 특정 문화권의 서식 규칙을 사용하여 문자열을 구문 분석하려면 오버로드를 호출 Parse(String, IFormatProvider) 합니다 Parse(String, IFormatProvider, DateTimeStyles) .

이 오버로드는 스타일을 사용하여 DateTimeStyles.AllowWhiteSpaces 구문 분석하려고 시도합니다s.

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

문자 범위를 값으로 구문 분석합니다.

public:
 static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<DateTime>::Parse;
public static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As DateTime

매개 변수

s
ReadOnlySpan<Char>

구문 분석할 문자의 범위입니다.

provider
IFormatProvider

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

반환

구문 분석의 결과입니다 s.

구현

적용 대상

Parse(String, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

문화권별 형식 정보를 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 형식으로 변환합니다.

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

매개 변수

s
String

변환할 날짜 및 시간이 들어 있는 문자열입니다. 자세한 내용은 구문 분석할 문자열 을 참조하세요.

provider
IFormatProvider

에 대한 문화권별 형식 정보를 제공하는 개체입니다 s. 구문 분석 및 문화권 규칙 참조

반환

에 지정된 provider날짜 및 시간에 s 해당하는 개체입니다.

구현

예외

snull입니다.

s 는 날짜 및 시간의 유효한 문자열 표현을 포함하지 않습니다.

예제

다음 예제에서는 en-US, fr-FR및 de-DE 문화권의 규칙을 사용하여 날짜 문자열 배열을 구문 분석합니다. 단일 날짜의 문자열 표현을 여러 문화권에서 다르게 해석할 수 있음을 보여 줍니다.

using System;
using System.Globalization;

public class ParseDate
{
   public static void Main()
   {
      // Define cultures to be used to parse dates.
      CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"),
                                CultureInfo.CreateSpecificCulture("fr-FR"),
                                CultureInfo.CreateSpecificCulture("de-DE")};
      // Define string representations of a date to be parsed.
      string[] dateStrings = {"01/10/2009 7:34 PM",
                              "10.01.2009 19:34",
                              "10-1-2009 19:34" };
      // Parse dates using each culture.
      foreach (CultureInfo culture in cultures)
      {
         DateTime dateValue;
         Console.WriteLine("Attempted conversions using {0} culture.",
                           culture.Name);
         foreach (string dateString in dateStrings)
         {
            try {
               dateValue = DateTime.Parse(dateString, culture);
               Console.WriteLine("   Converted '{0}' to {1}.",
                                 dateString, dateValue.ToString("f", culture));
            }
            catch (FormatException) {
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.",
                                 dateString, culture.Name);
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output to the console:
//       Attempted conversions using en-US culture.
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
//       Attempted conversions using fr-FR culture.
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
//       Attempted conversions using de-DE culture.
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
open System
open System.Globalization

// Define cultures to be used to parse dates.
let cultures = 
    [ CultureInfo.CreateSpecificCulture "en-US"
      CultureInfo.CreateSpecificCulture "fr-FR"
      CultureInfo.CreateSpecificCulture "de-DE" ]

// Define string representations of a date to be parsed.
let dateStrings = 
    [ "01/10/2009 7:34 PM"
      "10.01.2009 19:34"
      "10-1-2009 19:34" ]

// Parse dates using each culture.
for culture in cultures do
    printfn $"Attempted conversions using {culture.Name} culture."
    for dateString in dateStrings do
        try
            let dateValue = DateTime.Parse(dateString, culture)
            printfn $"""   Converted '{dateString}' to {dateValue.ToString("f", culture)}."""
        with :? FormatException ->
            printfn $"   Unable to convert '{dateString}' for culture {culture.Name}." 
    printfn ""


// The example displays the following output to the console:
//       Attempted conversions using en-US culture.
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
//       Attempted conversions using fr-FR culture.
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
//       Attempted conversions using de-DE culture.
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
Imports System.Globalization

Module ParseDate
   Public Sub Main()
      ' Define cultures to be used to parse dates.
      Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _
                                       CultureInfo.CreateSpecificCulture("fr-FR"), _
                                       CultureInfo.CreateSpecificCulture("de-DE")}
      ' Define string representations of a date to be parsed.
      Dim dateStrings() As String = {"01/10/2009 7:34 PM", _
                                     "10.01.2009 19:34", _
                                     "10-1-2009 19:34" }
      ' Parse dates using each culture.
      For Each culture In cultures
         Dim dateValue As Date
         Console.WriteLine("Attempted conversions using {0} culture.", culture.Name)
         For Each dateString As String In dateStrings
            Try
               dateValue = Date.Parse(dateString, culture)
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 dateString, dateValue.ToString("f", culture))
            Catch e As FormatException
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", _
                                 dateString, culture.Name)
            End Try                                                
         Next
         Console.WriteLine()
      Next                                                                                     
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversions using en-US culture.
'          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
'          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'       
'       Attempted conversions using fr-FR culture.
'          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
'          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
'          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
'       
'       Attempted conversions using de-DE culture.
'          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
'          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
'          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.

설명

표준 시간대 정보가 포함된 경우 s 이 메서드는 DateTimeKind.Local 속성이 있는 Kind 값을 반환 DateTime 하고 날짜와 시간을 현지 시간으로 s 변환합니다. 그렇지 않으면 표준 시간대 변환을 수행하지 않고 속성DateTimeKind.UnspecifiedKind 있는 DateTime 값을 반환합니다.

이 오버로드는 스타일을 사용하여 구문 분석 s 하려고 시도합니다 DateTimeStyles.AllowWhiteSpaces .

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

문화권별 형식 정보 및 서식 스타일을 사용하여 날짜 및 시간의 DateTime 문자열 표현이 포함된 메모리 범위를 해당 값으로 변환합니다.

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

매개 변수

s
ReadOnlySpan<Char>

구문 분석할 문자열이 포함된 메모리 범위입니다. 자세한 내용은 구문 분석할 문자열 을 참조하세요.

provider
IFormatProvider

에 대한 문화권별 형식 정보를 제공하는 개체입니다 s. 구문 분석 및 문화권 규칙 참조

styles
DateTimeStyles

구문 분석 작업이 성공하기 위해 존재 s 할 수 있는 스타일 요소를 나타내고 현재 표준 시간대 또는 현재 날짜와 관련하여 구문 분석된 날짜를 해석하는 방법을 정의하는 열거형 값의 비트 조합입니다. 지정하는 일반적인 값은 .입니다 None.

반환

지정된 날짜 및 시간에 해당하는 sproviderstyles개체입니다.

예외

s 는 날짜 및 시간의 유효한 문자열 표현을 포함하지 않습니다.

styles 에는 잘못된 값 조합이 DateTimeStyles 포함되어 있습니다. 예를 들어 AssumeLocalAssumeUniversal이 포함되어 있습니다.

적용 대상

Parse(String, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

문화권별 서식 정보와 서식 스타일을 사용하여 날짜 및 시간의 DateTime 문자열 표현을 해당 형식으로 변환합니다.

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

매개 변수

s
String

변환할 날짜 및 시간이 들어 있는 문자열입니다. 자세한 내용은 구문 분석할 문자열 을 참조하세요.

provider
IFormatProvider

에 대한 문화권별 서식 정보를 제공하는 개체입니다 s. 구문 분석 및 문화권 규칙 참조

styles
DateTimeStyles

구문 분석 작업이 성공하기 위해 존재 s 할 수 있는 스타일 요소를 나타내고 현재 표준 시간대 또는 현재 날짜와 관련하여 구문 분석된 날짜를 해석하는 방법을 정의하는 열거형 값의 비트 조합입니다. 지정하는 일반적인 값은 .입니다 None.

반환

지정된 날짜 및 시간에 해당하는 sproviderstyles개체입니다.

예외

snull입니다.

s 는 날짜 및 시간의 유효한 문자열 표현을 포함하지 않습니다.

styles 에는 잘못된 값 조합이 DateTimeStyles 포함되어 있습니다. 예를 들어 AssumeLocalAssumeUniversal이 포함되어 있습니다.

예제

다음 예제에서는 메서드를 Parse(String, IFormatProvider, DateTimeStyles) 보여 줍니다 및 결과 값의 Kind 속성 값을 표시 합니다 DateTime .

using System;
using System.Globalization;

public class ParseDateExample
{
   public static void Main()
   {
      string dateString;
      CultureInfo culture ;
      DateTimeStyles styles;
      DateTime result;

      // Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         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;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         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;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         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";
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         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;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         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
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse the same date and time with the AssumeLocal style.
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        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
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        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"
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        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
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        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

Module ParseDateExample
   Public Sub Main()
      Dim dateString As String  
      Dim culture As CultureInfo
      Dim styles As DateTimeStyles 
      Dim result 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
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' 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
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00"
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      

      ' 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
      Try
         result = DateTime.Parse(dateString, culture, styles)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
   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.

설명

이 메서드 오버로드는 날짜 및 시간을 s 변환하고 반환 DateTimeKind 값의 속성을 다음과 같이 설정합니다.

표준 시간대 변환 Kind 속성
s 에는 표준 시간대 정보가 없습니다. 없음. DateTimeKind.Unspecified
s 에는 표준 시간대 정보가 포함되어 있습니다. 현지 표준 시간대의 시간으로 DateTimeKind.Local
s 에는 표준 시간대 정보가 포함되고 styles 플래그가 DateTimeStyles.AdjustToUniversal 포함됩니다. UTC(협정 세계시)로 DateTimeKind.Utc
s에는 Z 또는 GMT 표준 시간대 지정자가 포함되어 DateTimeStyles.RoundtripKind있습니다styles. 없음. DateTimeKind.Utc

추가 정보

적용 대상