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.