Convert.ToDateTime Método

Definición

Convierte un valor especificado en un valor DateTime.

Sobrecargas

ToDateTime(Single)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(String)

Convierte la representación de cadena especificada de una fecha y hora en un valor de fecha y hora equivalente.

ToDateTime(UInt16)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(String, IFormatProvider)

Convierte la representación de cadena especificada de un número en una fecha y hora equivalente, usando la información de formato específica de la referencia cultural indicada.

ToDateTime(UInt64)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Object, IFormatProvider)

Convierte el valor del objeto especificado en un objeto DateTime, usando la información de formato específica de la referencia cultural indicada.

ToDateTime(SByte)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(UInt32)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Object)

Convierte el valor del objeto especificado en un objeto DateTime.

ToDateTime(Int16)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Int32)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Int64)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Double)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Decimal)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(DateTime)

Devuelve el objeto DateTime especificado; no se efectúa una conversión real.

ToDateTime(Char)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Byte)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Boolean)

Cuando se llama a este método, siempre se produce InvalidCastException.

ToDateTime(Single)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Single

Valor de punto flotante de precisión sencilla que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(String)

Convierte la representación de cadena especificada de una fecha y hora en un valor de fecha y hora equivalente.

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

Parámetros

value
String

Representación en forma de cadena de una fecha y hora.

Devoluciones

El equivalente de fecha y hora del valor de value, o el equivalente de fecha y hora de DateTime.MinValue si value es null.

Excepciones

value no es una cadena de hora y fecha de formato correcto.

Ejemplos

En el ejemplo siguiente se usa el ToDateTime método para convertir varias representaciones de cadena de fechas y horas en DateTime valores.

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.

Comentarios

Si value no nulles , el valor devuelto es el resultado de invocar el DateTime.Parse método al value usar la información de formato en un DateTimeFormatInfo objeto que se inicializa para la referencia cultural actual. El value argumento debe contener la representación de una fecha y hora en uno de los formatos descritos en el DateTimeFormatInfo tema. Si el valor de value es null, el método devuelve DateTime.MinValue.

Este método intenta analizar value completamente y evitar la iniciación de .FormatException Completa la información del mes, el día y el año que faltan con la fecha actual. Si value solo contiene una fecha y ninguna hora, este método supone una hora de medianoche. Se omiten los caracteres de espacio en blanco iniciales, internos o finales de value .

Si prefiere no controlar una excepción si se produce un error en la conversión, puede llamar al DateTime.TryParse método en su lugar. Devuelve un Boolean valor que indica si la conversión se realizó correctamente o no.

Consulte también

Se aplica a

ToDateTime(UInt16)

Importante

Esta API no es conforme a CLS.

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
UInt16

Entero de 16 bits sin signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Atributos

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(String, IFormatProvider)

Convierte la representación de cadena especificada de un número en una fecha y hora equivalente, usando la información de formato específica de la referencia cultural indicada.

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

Parámetros

value
String

Cadena que contiene una fecha y hora que se van a convertir.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

El equivalente de fecha y hora del valor de value, o el equivalente de fecha y hora de DateTime.MinValue si value es null.

Excepciones

value no es una cadena de hora y fecha de formato correcto.

Ejemplos

En el ejemplo siguiente se convierten representaciones de cadena de valores de fecha con el ToDateTime método , mediante un IFormatProvider objeto .

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

Comentarios

El valor devuelto es el resultado de invocar el DateTime.Parse(String, IFormatProvider) método en value.

provider es una IFormatProvider instancia de que obtiene un DateTimeFormatInfo objeto . El DateTimeFormatInfo objeto proporciona información específica de la referencia cultural sobre el formato de value. Si provider es null, se usa para DateTimeFormatInfo la referencia cultural actual.

Si prefiere no controlar una excepción si se produce un error en la conversión, puede llamar al DateTime.TryParse método en su lugar. Devuelve un Boolean valor que indica si la conversión se realizó correctamente o no.

Consulte también

Se aplica a

ToDateTime(UInt64)

Importante

Esta API no es conforme a CLS.

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
UInt64

Entero de 64 bits sin signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Atributos

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Object, IFormatProvider)

Convierte el valor del objeto especificado en un objeto DateTime, usando la información de formato específica de la referencia cultural indicada.

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

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

El equivalente de fecha y hora del valor de value, o el equivalente de fecha y hora de DateTime.MinValue si value es null.

Excepciones

value no es un valor de hora y fecha válida.

value no implementa la interfaz IConvertible.

O bien

No se admite la conversión.

Ejemplos

En el ejemplo siguiente se define un proveedor de formato personalizado, CustomProvider, cuyo GetFormat método genera un mensaje en la consola a la que se ha invocado y, a continuación, devuelve el DateTimeFormatInfo objeto de la referencia cultural cuyo nombre se pasó como parámetro a su constructor de clases. Cada uno de estos CustomProvider objetos se usa para convertir los elementos de una matriz de objetos en valores de fecha y hora. La salida indica que el CustomProvider objeto se usa en la conversión solo cuando el tipo del value parámetro es .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

Comentarios

El valor devuelto es el resultado de invocar el IConvertible.ToDateTime método del tipo subyacente de value.

provider permite al usuario especificar información de conversión específica de la referencia cultural sobre el contenido de value. Por ejemplo, si value es un String que representa una fecha, provider podría proporcionar información específica de la referencia cultural sobre la notación utilizada para representar esa fecha. provider está implicado en la conversión de si el tipo en tiempo de value ejecución de value es , Stringo si value es un tipo definido por el usuario cuya IConvertible.ToDateTime implementación hace uso de provider. Si el tipo en tiempo de ejecución de value es String y provider es null, se usa el CultureInfo objeto que representa la referencia cultural actual.

Consulte también

Se aplica a

ToDateTime(SByte)

Importante

Esta API no es conforme a CLS.

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
SByte

Entero de 8 bits con signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Atributos

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(UInt32)

Importante

Esta API no es conforme a CLS.

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
UInt32

Entero de 32 bits sin signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Atributos

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Object)

Convierte el valor del objeto especificado en un objeto 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

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible o null.

Devoluciones

El equivalente de fecha y hora del valor de value, o un equivalente de fecha y hora de DateTime.MinValue si value es null.

Excepciones

value no es un valor de hora y fecha válida.

value no implementa la interfaz IConvertible.

O bien

No se admite la conversión.

Ejemplos

En el ejemplo siguiente se llama al ToDateTime(Object) método con una variedad de Object variables.

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.

Comentarios

Para que la conversión se realice correctamente, el tipo de tiempo de ejecución del value parámetro debe ser o DateTime , Stringo value debe ser null. De lo contrario, el método produce una InvalidCastExceptionexcepción . Además, si value es una cadena, debe contener una representación válida de un valor de fecha y hora en la referencia cultural actual o se produce .FormatException

El valor devuelto es el resultado de invocar el IConvertible.ToDateTime método del tipo subyacente de value.

Se aplica a

ToDateTime(Int16)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Int16

Entero de 16 bits con signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Int32)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Int32

Entero de 32 bits con signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Int64)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Int64

Entero de 64 bits con signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Double)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Double

Valor de punto flotante de precisión doble que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Decimal)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Decimal

Número que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Se aplica a

ToDateTime(DateTime)

Devuelve el objeto DateTime especificado; no se efectúa una conversión real.

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

Parámetros

value
DateTime

Valor de fecha y hora.

Devoluciones

value se devuelve sin cambios.

Se aplica a

ToDateTime(Char)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Char

Carácter Unicode que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Byte)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Byte

Entero de 8 bits sin signo que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a

ToDateTime(Boolean)

Cuando se llama a este método, siempre se produce InvalidCastException.

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

Parámetros

value
Boolean

Valor booleano que se va a convertir.

Devoluciones

No se admite esta conversión. No se devuelve ningún valor.

Excepciones

No se admite esta conversión.

Consulte también

Se aplica a