C# Convert ToDateTime(String)

Description

Convert ToDateTime(String) converts the specified string representation of a date and time to an equivalent date and time value.

Syntax

Convert.ToDateTime(String) has the following syntax.


public static DateTime ToDateTime(
  string value
)

Parameters

Convert.ToDateTime(String) has the following parameters.

  • value - The string representation of a date and time.

Returns

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

Example

The following example uses the ToDateTime method to convert various string representations of dates and times to DateTime values.


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

public class ConversionToDateTime
{
   public static void Main()
   {
      string dateString = "05/01/2014";
      ConvertToDateTime(dateString);
      dateString = "Tue Apr 28, 2014";
      ConvertToDateTime(dateString);
      dateString = "Wed Apr 28, 2014";
      ConvertToDateTime(dateString);
      dateString = "06 July 2014 7:32:47 AM";
      ConvertToDateTime(dateString);
      dateString = "17:32:47.003";
      ConvertToDateTime(dateString);

      dateString = "Sat, 10 May 2008 14:32:17 GMT";
      ConvertToDateTime(dateString);

      dateString = "2014-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 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