C# Convert ToDateTime(Object)

Description

Convert ToDateTime(Object) converts the value of the specified object to a DateTime object.

Syntax

Convert.ToDateTime(Object) has the following syntax.


public static DateTime ToDateTime(
  Object value
)

Parameters

Convert.ToDateTime(Object) has the following parameters.

  • value - An object that implements the IConvertible interface, or null.

Returns

Convert.ToDateTime(Object) method returns The date and time equivalent of the value of value, or a date and time equivalent of DateTime.MinValue if value is null.

Example

The following example calls the ToDateTime(Object) method with a variety of Object variables.


using System;//  ww  w  . j  a  v a 2 s. co m

public class ConversionToDateTime
{
   public static void Main()
   {
      string nonDateString = "monthly";
      ConvertToDateTime(nonDateString);

      string dateString; 
      dateString = "05/01/2014";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2014";
      ConvertToDateTime(dateString);
      dateString = "06 July 2014 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 code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version