c# - How to convert a string to a datetime object

String to datetime
Convert.ToDateTime(String) method allow us to convert a string representation of a date and time to its equivalent date and time value. this method exists in System namespace. the Convert.ToDateTime(String) method require to pass a parameter name 'value'. this 'value' parameter data type is System.String. this string contains the date and time value as string representation.

the method return value data type is System.DateTime. the DateTime return value is equivalent of the parameter value. if the parameter 'value' is null then the method return DateTime.MinValue. the method throw a 'FormatException' exception when parameter not pass a properly formatted date and time string.

the following .net c# example code demonstrate us how can we convert a string object to its equivalent datetime object.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.  
        string dateString = "8/12/1977";  
        Label1.Text = "string of date..................<br />";
        Label1.Text += dateString;

        //this line convert/parse string to date time object.
        DateTime dateObject = Convert.ToDateTime(dateString);

        Label1.Text += "<br /><br />converted date time object from string.........<br />";
        Label1.Text += dateObject;
        Label1.Text += "<br />" + string.Format("{0:d}", dateObject);
        Label1.Text += "<br />" + string.Format("{0:D}", dateObject);
        Label1.Text += "<br />" + string.Format("{0:Y}", dateObject);
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string to datetime</title>    
    <form id="form1" runat="server">    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - string to datetime
        <hr width="550" align="left" color="Gainsboro" />    
        <br /><br />  
            Text="string to datetime"    
More c# examples