Convert.ToDateTime 메서드

정의

지정된 값을 DateTime 값으로 변환합니다.

오버로드

ToDateTime(Single)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(String)

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

ToDateTime(UInt16)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(String, IFormatProvider)

지정된 문화권별 서식 지정 정보를 사용하여, 숫자의 지정된 문자열 표현을 해당하는 날짜와 시간으로 변환합니다.

ToDateTime(UInt64)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Object, IFormatProvider)

지정된 문화권별 서식 지정 정보를 사용하여, 지정된 개체의 값을 DateTime 개체로 변환합니다.

ToDateTime(SByte)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(UInt32)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Object)

지정된 개체의 값을 DateTime 개체로 변환합니다.

ToDateTime(Int16)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Int32)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Int64)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Double)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Decimal)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(DateTime)

지정된 DateTime 개체를 실제 변환 작업 없이 반환합니다.

ToDateTime(Char)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Byte)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Boolean)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

ToDateTime(Single)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(float value);
public static DateTime ToDateTime (float value);
static member ToDateTime : single -> DateTime
Public Shared Function ToDateTime (value As Single) As DateTime

매개 변수

value
Single

변환할 단정밀도 부동 소수점 값입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(String)

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

public:
 static DateTime ToDateTime(System::String ^ value);
public static DateTime ToDateTime (string value);
public static DateTime ToDateTime (string? value);
static member ToDateTime : string -> DateTime
Public Shared Function ToDateTime (value As String) As DateTime

매개 변수

value
String

날짜 및 시간의 문자열 표현입니다.

반환

value에 해당하는 날짜 및 시간 또는 이 인 경우 valuenullDateTime.MinValue에 해당하는 날짜 및 시간입니다.

예외

value가 올바른 형식의 날짜 및 시간 문자열이 아닙니다.

예제

다음 예제에서는 메서드를 ToDateTime 사용하여 날짜 및 시간의 다양한 문자열 표현을 값으로 DateTime 변환합니다.

using System;

public class ConversionToDateTime
{
   public static void Main()
   {
      string dateString = null;

      // Convert a null string.
      ConvertToDateTime(dateString);

      // Convert an empty string.
      dateString = String.Empty;
      ConvertToDateTime(dateString);

      // Convert a non-date string.
      dateString = "not a date";
      ConvertToDateTime(dateString);

      // Try to convert various date strings.
      dateString = "05/01/1996";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "Wed Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "06 July 2008 7:32:47 AM";
      ConvertToDateTime(dateString);
      dateString = "17:32:47.003";
      ConvertToDateTime(dateString);
      // Convert a string returned by DateTime.ToString("R").
      dateString = "Sat, 10 May 2008 14:32:17 GMT";
      ConvertToDateTime(dateString);
      // Convert a string returned by DateTime.ToString("o").
      dateString = "2009-05-01T07:54:59.9843750-04:00";
      ConvertToDateTime(dateString);
   }

   private static void ConvertToDateTime(string value)
   {
      DateTime convertedDate;
      try {
         convertedDate = Convert.ToDateTime(value);
         Console.WriteLine("'{0}' converts to {1} {2} time.",
                           value, convertedDate,
                           convertedDate.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in the proper format.", value);
      }
   }
}
// The example displays the following output:
//    '' converts to 1/1/0001 12:00:00 AM Unspecified time.
//    '' is not in the proper format.
//    'not a date' is not in the proper format.
//    '05/01/1996' converts to 5/1/1996 12:00:00 AM Unspecified time.
//    'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM Unspecified time.
//    'Wed Apr 28, 2009' is not in the proper format.
//    '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM Unspecified time.
//    '17:32:47.003' converts to 5/30/2008 5:32:47 PM Unspecified time.
//    'Sat, 10 May 2008 14:32:17 GMT' converts to 5/10/2008 7:32:17 AM Local time.
//    '2009-05-01T07:54:59.9843750-04:00' converts to 5/1/2009 4:54:59 AM Local time.
open System

let convertToDateTime (value: string) =
    try
        let convertedDate = Convert.ToDateTime value
        printfn $"'{value}' converts to {convertedDate} {convertedDate.Kind} time."
    with :?FormatException ->
        printfn $"'{value}' is not in the proper format."

[<EntryPoint>]
let main _ =
    let dateString = null

    // Convert a null string.
    convertToDateTime dateString

    // Convert an empty string.
    let dateString = String.Empty
    convertToDateTime dateString

    // Convert a non-date string.
    let dateString = "not a date"
    convertToDateTime dateString

    // Try to convert various date strings.
    let dateString = "05/01/1996"
    convertToDateTime dateString
    let dateString = "Tue Apr 28, 2009"
    convertToDateTime dateString
    let dateString = "Wed Apr 28, 2009"
    convertToDateTime dateString
    let dateString = "06 July 2008 7:32:47 AM"
    convertToDateTime dateString
    let dateString = "17:32:47.003"
    convertToDateTime dateString
    // Convert a string returned by DateTime.ToString("R").
    let dateString = "Sat, 10 May 2008 14:32:17 GMT"
    convertToDateTime dateString
    // Convert a string returned by DateTime.ToString("o").
    let dateString = "2009-05-01T07:54:59.9843750-04:00"
    convertToDateTime dateString

    0

// The example displays the following output:
//    '' converts to 1/1/0001 12:00:00 AM Unspecified time.
//    '' is not in the proper format.
//    'not a date' is not in the proper format.
//    '05/01/1996' converts to 5/1/1996 12:00:00 AM Unspecified time.
//    'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM Unspecified time.
//    'Wed Apr 28, 2009' is not in the proper format.
//    '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM Unspecified time.
//    '17:32:47.003' converts to 5/30/2008 5:32:47 PM Unspecified time.
//    'Sat, 10 May 2008 14:32:17 GMT' converts to 5/10/2008 7:32:17 AM Local time.
//    '2009-05-01T07:54:59.9843750-04:00' converts to 5/1/2009 4:54:59 AM Local time.
Module ConversionToDateTime
   Public Sub Main()
      Dim dateString As String = Nothing
      
      ' Convert a null string.
      ConvertToDateTime(dateString)
      
      ' Convert an empty string.
      dateString = String.Empty
      ConvertToDateTime(dateString)
      
      ' Convert a non-date string.
      dateString = "not a date"
      ConvertToDateTime(dateString)
      
      ' Try to convert various date strings.
      dateString = "05/01/1996"
      ConvertToDateTime(dateString)
      dateString = "Tue Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "Wed Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "06 July 2008 7:32:47 AM"
      ConvertToDateTime(dateString)
      dateString = "17:32:47.003"
      ConvertToDateTime(dateString)
      ' Convert a string returned by DateTime.ToString("R").
      dateString = "Sat, 10 May 2008 14:32:17 GMT"
      ConvertToDateTime(dateString)
      ' Convert a string returned by DateTime.ToString("o")
      dateString = "2009-05-01T07:54:59.9843750-04:00"
      ConvertToDateTime(dateString)
   End Sub
   
   Private Sub ConvertToDateTime(value As String)
      Dim convertedDate As Date
      Try
         convertedDate = Convert.ToDateTime(value)
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in the proper format.", value)
      End Try
   End Sub
End Module
' The example displays the following output:
'    '' converts to 1/1/0001 12:00:00 AM.
'    '' is not in the proper format.
'    'not a date' is not in the proper format.
'    '05/01/1996' converts to 5/1/1996 12:00:00 AM.
'    'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
'    'Wed Apr 28, 2009' is not in the proper format.
'    '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
'    '17:32:47.003' converts to 5/30/2008 5:32:47 PM.
'    'Sat, 10 May 2008 14:32:17 GMT' converts to 5/10/2008 7:32:17 AM.
'    '2009-05-01T07:54:59.9843750-04:00' converts to 5/1/2009 4:54:59 AM.

설명

이 아닌 경우 value 반환 값은 현재 문화권에 대해 value 초기화된 개체에서 DateTimeFormatInfo 서식 정보를 사용할 때 메서드를 호출 DateTime.Parse 한 결과null입니다. 인수는 value 토픽에 설명된 형식 중 하나로 날짜 및 시간의 표현을 DateTimeFormatInfo 포함해야 합니다. valuenull이면 메서드에서 DateTime.MinValue을 반환합니다.

이 메서드는 완전히 구문 분석 value 하 고 throw 하지 않도록 하려고 합니다.FormatException 누락된 월, 일 및 연도 정보를 현재 날짜로 완료합니다. 날짜와 시간만 포함된 경우 value 이 메서드는 자정을 가정합니다. 의 value 선행, 내부 또는 후행 공백 문자는 무시됩니다.

변환이 실패할 경우 예외를 처리하지 않으려는 경우 메서드를 대신 호출할 DateTime.TryParse 수 있습니다. 변환이 Boolean 성공했는지 실패했는지 여부를 나타내는 값을 반환합니다.

추가 정보

적용 대상

ToDateTime(UInt16)

중요

이 API는 CLS 규격이 아닙니다.

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::UInt16 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (ushort value);
[<System.CLSCompliant(false)>]
static member ToDateTime : uint16 -> DateTime
Public Shared Function ToDateTime (value As UShort) As DateTime

매개 변수

value
UInt16

변환할 16비트 부호 없는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

특성

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(String, IFormatProvider)

지정된 문화권별 서식 지정 정보를 사용하여, 숫자의 지정된 문자열 표현을 해당하는 날짜와 시간으로 변환합니다.

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

매개 변수

value
String

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

provider
IFormatProvider

문화권별 형식 정보를 제공하는 개체입니다.

반환

value에 해당하는 날짜 및 시간 또는 이 인 경우 valuenullDateTime.MinValue에 해당하는 날짜 및 시간입니다.

예외

value가 올바른 형식의 날짜 및 시간 문자열이 아닙니다.

예제

다음 예제에서는 개체를 사용하여 날짜 값의 문자열 표현을 ToDateTime 메서드로 IFormatProvider 변환합니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,-18}{1,-12}{2}\n", "Date String", "Culture", "Result");

      string[] cultureNames = { "en-US", "ru-RU","ja-JP" };
      string[] dateStrings = { "01/02/09", "2009/02/03",  "01/2009/03",
                               "01/02/2009", "21/02/09", "01/22/09",
                               "01/02/23" };
      // Iterate each culture name in the array.
      foreach (string cultureName in cultureNames)
      {
         CultureInfo culture = new CultureInfo(cultureName);

         // Parse each date using the designated culture.
         foreach (string dateStr in dateStrings)
         {
            DateTime dateTimeValue;
            try {
               dateTimeValue = Convert.ToDateTime(dateStr, culture);
                // Display the date and time in a fixed format.
                Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}",
                                  dateStr, cultureName, dateTimeValue);
            }
            catch (FormatException e) {
                Console.WriteLine("{0,-18}{1,-12}{2}",
                                  dateStr, cultureName, e.GetType().Name);
            }
         }
         Console.WriteLine();
      }
   }
}
open System
open System.Globalization

printfn $"""{"Date String",-18}{"Culture",-12}{"Result"}\n"""

let cultureNames = [ "en-US"; "ru-RU"; "ja-JP" ]
let dateStrings =
    [ "01/02/09"; "2009/02/03"; "01/2009/03"
      "01/02/2009"; "21/02/09"; "01/22/09"; "01/02/23" ]
// Iterate each culture name in the array.
for cultureName in cultureNames do
    let culture = CultureInfo cultureName

    // Parse each date using the designated culture.
    for dateStr in dateStrings do
        try
            let dateTimeValue = Convert.ToDateTime(dateStr, culture)
            // Display the date and time in a fixed format.
            printfn $"""{dateStr,-18}{cultureName,-12}{dateTimeValue.ToString "yyyy-MMM-dd"}"""
        with :? FormatException as e ->
            printfn $"{dateStr,-18}{cultureName,-12}{e.GetType().Name}"
    printfn ""
Imports System.Globalization

Module Example
   Public Sub Main( )
      Console.WriteLine("{0,-18}{1,-12}{2}", "Date String", "Culture", "Result")
      Console.WriteLine()

      Dim cultureNames() As String = { "en-US", "ru-RU","ja-JP" }
      Dim dateStrings() As String = { "01/02/09", "2009/02/03",  "01/2009/03", _
                                      "01/02/2009", "21/02/09", "01/22/09",   _
                                      "01/02/23" }
      ' Iterate each culture name in the array.
      For Each cultureName As String In cultureNames
         Dim culture As CultureInfo = New CultureInfo(cultureName)
        
         ' Parse each date using the designated culture.
         For Each dateStr As String In dateStrings
            Dim dateTimeValue As DateTime
            Try
               dateTimeValue = Convert.ToDateTime(dateStr, culture)
                ' Display the date and time in a fixed format.
                Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}", _
                                  dateStr, cultureName, dateTimeValue)
            Catch e As FormatException 
                Console.WriteLine("{0,-18}{1,-12}{2}", _
                                  dateStr, cultureName, e.GetType().Name)
            End Try            
         Next
         Console.WriteLine()
      Next
   End Sub 
End Module 
' The example displays the following output:
'       Date String       Culture     Result
'       
'       01/02/09          en-US       2009-Jan-02
'       2009/02/03        en-US       2009-Feb-03
'       01/2009/03        en-US       2009-Jan-03
'       01/02/2009        en-US       2009-Jan-02
'       21/02/09          en-US       FormatException
'       01/22/09          en-US       2009-Jan-22
'       01/02/23          en-US       2023-Jan-02
'       
'       01/02/09          ru-RU       2009-Feb-01
'       2009/02/03        ru-RU       2009-Feb-03
'       01/2009/03        ru-RU       2009-Jan-03
'       01/02/2009        ru-RU       2009-Feb-01
'       21/02/09          ru-RU       2009-Feb-21
'       01/22/09          ru-RU       FormatException
'       01/02/23          ru-RU       2023-Feb-01
'       
'       01/02/09          ja-JP       2001-Feb-09
'       2009/02/03        ja-JP       2009-Feb-03
'       01/2009/03        ja-JP       2009-Jan-03
'       01/02/2009        ja-JP       2009-Jan-02
'       21/02/09          ja-JP       2021-Feb-09
'       01/22/09          ja-JP       FormatException
'       01/02/23          ja-JP       2001-Feb-23

설명

반환 값은 에서 메서드를 호출한 DateTime.Parse(String, IFormatProvider) 결과입니다 value.

provider는 개체를 IFormatProvider 가져오는 DateTimeFormatInfo instance. 개체는 DateTimeFormatInfo 형식 value에 대한 문화권별 정보를 제공합니다. 가 이 nullDateTimeFormatInfoprovider 현재 문화권의 가 사용됩니다.

변환이 실패할 경우 예외를 처리하지 않으려는 경우 메서드를 대신 호출할 DateTime.TryParse 수 있습니다. 변환이 Boolean 성공했는지 실패했는지 여부를 나타내는 값을 반환합니다.

추가 정보

적용 대상

ToDateTime(UInt64)

중요

이 API는 CLS 규격이 아닙니다.

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::UInt64 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (ulong value);
[<System.CLSCompliant(false)>]
static member ToDateTime : uint64 -> DateTime
Public Shared Function ToDateTime (value As ULong) As DateTime

매개 변수

value
UInt64

변환할 64비트 부호 없는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

특성

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Object, IFormatProvider)

지정된 문화권별 서식 지정 정보를 사용하여, 지정된 개체의 값을 DateTime 개체로 변환합니다.

public:
 static DateTime ToDateTime(System::Object ^ value, IFormatProvider ^ provider);
public static DateTime ToDateTime (object value, IFormatProvider provider);
public static DateTime ToDateTime (object? value, IFormatProvider? provider);
static member ToDateTime : obj * IFormatProvider -> DateTime
Public Shared Function ToDateTime (value As Object, provider As IFormatProvider) As DateTime

매개 변수

value
Object

IConvertible 인터페이스를 구현하는 개체

provider
IFormatProvider

문화권별 형식 정보를 제공하는 개체입니다.

반환

value에 해당하는 날짜 및 시간 또는 이 인 경우 valuenullDateTime.MinValue에 해당하는 날짜 및 시간입니다.

예외

value가 올바른 날짜 및 시간 값이 아닙니다.

valueIConvertible 인터페이스를 구현하지 않습니다.

또는

이 변환은 지원되지 않습니다.

예제

다음 예제에서는 메서드가 호출된 콘솔에 메시지를 출력한 다음 이름이 해당 클래스 생성자에 매개 변수로 전달된 문화권의 개체를 반환 DateTimeFormatInfo 하는 사용자 지정 형식 공급자 CustomProviderGetFormat 를 정의합니다. 이러한 CustomProvider 각 개체는 개체 배열의 요소를 날짜 및 시간 값으로 변환하는 데 사용됩니다. 출력은 매개 변수의 CustomProvider 형식이 인 경우에만 개체가 변환에 value 사용됨을 String나타냅니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "hu-HU", "pt-PT" };
      object[] objects = { 12, 17.2, false, new DateTime(2010, 1, 1), "today",
                           new System.Collections.ArrayList(), 'c',
                           "05/10/2009 6:13:18 PM", "September 8, 1899" };

      foreach (string cultureName in cultureNames)
      {
         Console.WriteLine("{0} culture:", cultureName);
         CustomProvider provider = new CustomProvider(cultureName);
         foreach (object obj in objects)
         {
            try {
               DateTime dateValue = Convert.ToDateTime(obj, provider);
               Console.WriteLine("{0} --> {1}", obj,
                                 dateValue.ToString(new CultureInfo(cultureName)));
            }
            catch (FormatException) {
               Console.WriteLine("{0} --> Bad Format", obj);
            }
            catch (InvalidCastException) {
               Console.WriteLine("{0} --> Conversion Not Supported", obj);
            }
         }
         Console.WriteLine();
      }
   }
}

public class CustomProvider : IFormatProvider
{
   private string cultureName;

   public CustomProvider(string cultureName)
   {
      this.cultureName = cultureName;
   }

   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(DateTimeFormatInfo))
      {
         Console.Write("(CustomProvider retrieved.) ");
         return new CultureInfo(cultureName).GetFormat(formatType);
      }
      else
      {
         return null;
      }
   }
}
// The example displays the following output:
//    en-US culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 1/1/2010 12:00:00 AM
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 5/10/2009 6:13:18 PM
//    (CustomProvider retrieved.) September 8, 1899 --> 9/8/1899 12:00:00 AM
//
//    hu-HU culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 2010. 01. 01. 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 2009. 05. 10. 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 1899. 09. 08. 0:00:00
//
//    pt-PT culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 01-01-2010 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 05-10-2009 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 08-09-1899 0:00:00
open System
open System.Globalization

type CustomProvider(cultureName: string) =
    interface IFormatProvider with
        member _.GetFormat(formatType) =
            if formatType = typeof<DateTimeFormatInfo> then
                printf "(CustomProvider retrieved.) "
                CultureInfo(cultureName).GetFormat formatType
            else
                null

let cultureNames = [ "en-US"; "hu-HU"; "pt-PT" ]
let objects: obj list =
    [ 12; 17.2; false; DateTime(2010, 1, 1); "today"
      System.Collections.ArrayList(); 'c'
      "05/10/2009 6:13:18 PM"; "September 8, 1899" ]

for cultureName in cultureNames do
    printfn $"{cultureName} culture:"
    let provider = CustomProvider cultureName
    for obj in objects do
        try
            let dateValue = Convert.ToDateTime(obj, provider)
            printfn $"{obj} --> {dateValue.ToString(CultureInfo cultureName)}"
        with
        | :? FormatException ->
            printfn $"{obj} --> Bad Format"
        | :? InvalidCastException ->
            printfn $"{obj} --> Conversion Not Supported"
    printfn ""

// The example displays the following output:
//    en-US culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 1/1/2010 12:00:00 AM
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 5/10/2009 6:13:18 PM
//    (CustomProvider retrieved.) September 8, 1899 --> 9/8/1899 12:00:00 AM
//
//    hu-HU culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 2010. 01. 01. 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 2009. 05. 10. 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 1899. 09. 08. 0:00:00
//
//    pt-PT culture:
//    12 --> Conversion Not Supported
//    17.2 --> Conversion Not Supported
//    False --> Conversion Not Supported
//    1/1/2010 12:00:00 AM --> 01-01-2010 0:00:00
//    (CustomProvider retrieved.) today --> Bad Format
//    System.Collections.ArrayList --> Conversion Not Supported
//    c --> Conversion Not Supported
//    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 05-10-2009 18:13:18
//    (CustomProvider retrieved.) September 8, 1899 --> 08-09-1899 0:00:00
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "hu-HU", "pt-PT" }
      Dim objects() As Object = { 12, 17.2, False, #1/1/2010#, "today", _
                                  New System.Collections.ArrayList(), "c"c, _
                                  "05/10/2009 6:13:18 PM", "September 8, 1899" }
      
      For Each cultureName As String In cultureNames
         Console.WriteLine("{0} culture:", cultureName)
         Dim provider As New CustomProvider(cultureName)
         For Each obj As Object In objects
            Try
               Dim dateValue As Date = Convert.ToDateTime(obj, provider)      
               Console.WriteLine("{0} --> {1}", obj, _
                                 dateValue.ToString(New CultureInfo(cultureName)))
            Catch e As FormatException
               Console.WriteLine("{0} --> Bad Format", obj)
            Catch e As InvalidCastException
               Console.WriteLine("{0} --> Conversion Not Supported", obj)
            End Try
         Next
         Console.WriteLine()
      Next
   End Sub
End Module

Public Class CustomProvider : Implements IFormatProvider
   Private cultureName As String
   
   Public Sub New(cultureName As String)
      Me.cultureName = cultureName
   End Sub
   
   Public Function GetFormat(formatType As Type) As Object _
          Implements IFormatProvider.GetFormat
      If formatType Is GetType(DateTimeFormatInfo) Then
         Console.Write("(CustomProvider retrieved.) ")
         Return New CultureInfo(cultureName).GetFormat(formatType)
      Else
         Return Nothing
      End If   
   End Function
End Class
' The example displays the following output:
'    en-US culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 1/1/2010 12:00:00 AM
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 5/10/2009 6:13:18 PM
'    (CustomProvider retrieved.) September 8, 1899 --> 9/8/1899 12:00:00 AM
'    
'    hu-HU culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 2010. 01. 01. 0:00:00
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 2009. 05. 10. 18:13:18
'    (CustomProvider retrieved.) September 8, 1899 --> 1899. 09. 08. 0:00:00
'    
'    pt-PT culture:
'    12 --> Conversion Not Supported
'    17.2 --> Conversion Not Supported
'    False --> Conversion Not Supported
'    1/1/2010 12:00:00 AM --> 01-01-2010 0:00:00
'    (CustomProvider retrieved.) today --> Bad Format
'    System.Collections.ArrayList --> Conversion Not Supported
'    c --> Conversion Not Supported
'    (CustomProvider retrieved.) 05/10/2009 6:13:18 PM --> 05-10-2009 18:13:18
'    (CustomProvider retrieved.) September 8, 1899 --> 08-09-1899 0:00:00

설명

반환 값은 의 기본 형식의 IConvertible.ToDateTime 메서드를 호출한 결과입니다 value.

provider 를 사용하면 사용자가 의 value콘텐츠에 대한 문화권별 변환 정보를 지정할 수 있습니다. 예를 들어 가 날짜를 나타내는 인 경우 valueString 는 해당 날짜를 provider 나타내는 데 사용되는 표기법과 관련된 문화권별 정보를 제공할 수 있습니다. provider는 의 Stringvalue 런타임 형식이 이거나 가 구현에서 를 사용하는 사용자 정의 형식 IConvertible.ToDateTime 인 경우 valueprovider변환 value 과 관련이 있습니다. 의 value 런타임 형식이 String 이고 providernullCultureInfo 면 현재 문화권을 나타내는 개체가 사용됩니다.

추가 정보

적용 대상

ToDateTime(SByte)

중요

이 API는 CLS 규격이 아닙니다.

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::SByte value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (sbyte value);
[<System.CLSCompliant(false)>]
static member ToDateTime : sbyte -> DateTime
Public Shared Function ToDateTime (value As SByte) As DateTime

매개 변수

value
SByte

변환할 8비트 부호 있는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

특성

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(UInt32)

중요

이 API는 CLS 규격이 아닙니다.

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::UInt32 value);
[System.CLSCompliant(false)]
public static DateTime ToDateTime (uint value);
[<System.CLSCompliant(false)>]
static member ToDateTime : uint32 -> DateTime
Public Shared Function ToDateTime (value As UInteger) As DateTime

매개 변수

value
UInt32

변환할 32비트 부호 없는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

특성

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Object)

지정된 개체의 값을 DateTime 개체로 변환합니다.

public:
 static DateTime ToDateTime(System::Object ^ value);
public static DateTime ToDateTime (object value);
public static DateTime ToDateTime (object? value);
static member ToDateTime : obj -> DateTime
Public Shared Function ToDateTime (value As Object) As DateTime

매개 변수

value
Object

IConvertible 인터페이스를 구현하는 개체나 null입니다.

반환

value에 해당하는 날짜 및 시간 또는 이 인 경우 valuenullDateTime.MinValue에 해당하는 날짜 및 시간입니다.

예외

value가 올바른 날짜 및 시간 값이 아닙니다.

valueIConvertible 인터페이스를 구현하지 않습니다.

또는

이 변환은 지원되지 않습니다.

예제

다음 예제에서는 다양한 Object 변수를 ToDateTime(Object) 사용하여 메서드를 호출합니다.

using System;

public class ConversionToDateTime
{
   public static void Main()
   {
      // Try converting an integer.
      int number = 16352;
      ConvertToDateTime(number);

      // Convert a null.
      object obj = null;
      ConvertToDateTime(obj);

      // Convert a non-date string.
      string nonDateString = "monthly";
      ConvertToDateTime(nonDateString);

      // Try to convert various date strings.
      string dateString;
      dateString = "05/01/1996";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2009";
      ConvertToDateTime(dateString);
      dateString = "06 July 2008 7:32:47 AM";
      ConvertToDateTime(dateString);
      dateString = "17:32:47.003";
      ConvertToDateTime(dateString);
   }

   private static void ConvertToDateTime(object value)
   {
      DateTime convertedDate;
      try {
         convertedDate = Convert.ToDateTime(value);
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}' is not in the proper format.", value);
      }
      catch (InvalidCastException) {
         Console.WriteLine("Conversion of the {0} '{1}' is not supported",
                           value.GetType().Name, value);
      }
   }
}
// The example displays the following output:
//       Conversion of the Int32 '16352' is not supported
//       '' converts to 1/1/0001 12:00:00 AM.
//       'monthly' is not in the proper format.
//       '05/01/1996' converts to 5/1/1996 12:00:00 AM.
//       'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
//       '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
//       '17:32:47.003' converts to 5/28/2008 5:32:47 PM.
open System

let convertToDateTime (value: obj) =
    try
        let convertedDate = Convert.ToDateTime value
        printfn $"'{value}' converts to {convertedDate}."
    with
    | :? FormatException ->
        printfn $"'{value}' is not in the proper format."
    | :? InvalidCastException ->
        printfn $"Conversion of the {value.GetType().Name} '{value}' is not supported"

[<EntryPoint>]
let main _ =
    // Try converting an integer.
    let number = 16352
    convertToDateTime number

    // Convert a null.
    let obj = box null
    convertToDateTime obj

    // Convert a non-date string.
    let nonDateString = "monthly"
    convertToDateTime nonDateString

    // Try to convert various date strings.
    let dateString = "05/01/1996"
    convertToDateTime dateString
    let dateString = "Tue Apr 28, 2009"
    convertToDateTime dateString
    let dateString = "06 July 2008 7:32:47 AM"
    convertToDateTime dateString
    let dateString = "17:32:47.003"
    convertToDateTime dateString

    0

// The example displays the following output:
//       Conversion of the Int32 '16352' is not supported
//       '' converts to 1/1/0001 12:00:00 AM.
//       'monthly' is not in the proper format.
//       '05/01/1996' converts to 5/1/1996 12:00:00 AM.
//       'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
//       '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
//       '17:32:47.003' converts to 5/28/2008 5:32:47 PM.
Module ConversionToDateTime
   Public Sub Main()
      ' Try converting an integer.
      Dim number As Integer = 16352
      ConvertToDateTime(number)
      
      ' Convert a null.
      Dim obj As Object = Nothing
      ConvertToDateTime(obj)
      
      ' Convert a non-date string.
      Dim nonDateString As String = "monthly"
      ConvertToDateTime(nonDateString)
      
      ' Try to convert various dates.
      Dim dateString As String 
      dateString = "05/01/1996"
      ConvertToDateTime(dateString)
      dateString = "Tue Apr 28, 2009"
      ConvertToDateTime(dateString)
      dateString = "06 July 2008 7:32:47 AM"
      ConvertToDateTime(dateString)
      dateString = "17:32:47.003"
      ConvertToDateTime(dateString)
   End Sub
   
   Private Sub ConvertToDateTime(value As Object)
      Dim convertedDate As Date
      Try
         convertedDate = Convert.ToDateTime(value)
         Console.WriteLine("'{0}' converts to {1}.", value, convertedDate)
      Catch e As FormatException
         Console.WriteLine("'{0}' is not in the proper format.", value)
      Catch e As InvalidCastException
         Console.WriteLine("Conversion of the {0} '{1}' is not supported", _
                           value.GetType().Name, value)
      End Try
   End Sub
End Module
' The example displays the following output:
'       Conversion of the Int32 '16352' is not supported
'       '' converts to 1/1/0001 12:00:00 AM.
'       'monthly' is not in the proper format.
'       '05/01/1996' converts to 5/1/1996 12:00:00 AM.
'       'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
'       '06 July 2008 7:32:47 AM' converts to 7/6/2008 7:32:47 AM.
'       '17:32:47.003' converts to 5/28/2008 5:32:47 PM.

설명

변환이 성공하려면 매개 변수의 런타임 형식이 value 또는 Stringvalue 이거나 이어야 DateTime 합니다null. 그렇지 않으면 메서드가 을 InvalidCastExceptionthrow합니다. 또한 가 문자열인 경우 value 현재 문화권에서 날짜 및 시간 값의 유효한 표현을 포함해야 합니다. 그렇지 않으면 이 FormatException throw됩니다.

반환 값은 의 기본 형식의 IConvertible.ToDateTime 메서드를 호출한 결과입니다 value.

적용 대상

ToDateTime(Int16)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(short value);
public static DateTime ToDateTime (short value);
static member ToDateTime : int16 -> DateTime
Public Shared Function ToDateTime (value As Short) As DateTime

매개 변수

value
Int16

변환할 16비트 부호 있는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Int32)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(int value);
public static DateTime ToDateTime (int value);
static member ToDateTime : int -> DateTime
Public Shared Function ToDateTime (value As Integer) As DateTime

매개 변수

value
Int32

변환할 32비트 부호 있는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Int64)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(long value);
public static DateTime ToDateTime (long value);
static member ToDateTime : int64 -> DateTime
Public Shared Function ToDateTime (value As Long) As DateTime

매개 변수

value
Int64

변환할 64비트 부호 있는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Double)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(double value);
public static DateTime ToDateTime (double value);
static member ToDateTime : double -> DateTime
Public Shared Function ToDateTime (value As Double) As DateTime

매개 변수

value
Double

변환할 배정밀도 부동 소수점 값입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Decimal)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::Decimal value);
public static DateTime ToDateTime (decimal value);
static member ToDateTime : decimal -> DateTime
Public Shared Function ToDateTime (value As Decimal) As DateTime

매개 변수

value
Decimal

변환할 숫자입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

적용 대상

ToDateTime(DateTime)

지정된 DateTime 개체를 실제 변환 작업 없이 반환합니다.

public:
 static DateTime ToDateTime(DateTime value);
public static DateTime ToDateTime (DateTime value);
static member ToDateTime : DateTime -> DateTime
Public Shared Function ToDateTime (value As DateTime) As DateTime

매개 변수

value
DateTime

날짜 및 시간 값입니다.

반환

value를 변경하지 않고 반환합니다.

적용 대상

ToDateTime(Char)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(char value);
public static DateTime ToDateTime (char value);
static member ToDateTime : char -> DateTime
Public Shared Function ToDateTime (value As Char) As DateTime

매개 변수

value
Char

변환할 유니코드 문자입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Byte)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(System::Byte value);
public static DateTime ToDateTime (byte value);
static member ToDateTime : byte -> DateTime
Public Shared Function ToDateTime (value As Byte) As DateTime

매개 변수

value
Byte

변환할 8비트 부호 없는 정수입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상

ToDateTime(Boolean)

이 메서드를 호출하면 InvalidCastException이 항상 throw됩니다.

public:
 static DateTime ToDateTime(bool value);
public static DateTime ToDateTime (bool value);
static member ToDateTime : bool -> DateTime
Public Shared Function ToDateTime (value As Boolean) As DateTime

매개 변수

value
Boolean

변환할 부울 값입니다.

반환

이 변환은 지원되지 않습니다. 값이 반환되지 않습니다.

예외

이 변환은 지원되지 않습니다.

추가 정보

적용 대상