How to convert a string to datetime in c#


When we have date as a form of string and we want to convert them in Date Time format. Then we can use system’s convert class to convert which is most widely used to convert many values data type. The associated ToDateTime method is then used to convert the string date value to DateTime data type. In this ‘ToDatetime’ function string Date is passed as a parameter this will return converted DateTime value.

                Some Important things which you Should know which help you get desired result. This is that Date are converted here according to current culture of you computer or the machine having the compiler. Like in following example en-US will read following Date string as January 8 2012, and in fr-FR it is converted as August 1 2012. So you can tell the system  to use which culture using Iformateprovider class. Following is the way to define your culture. 

 C# |  copy code |? 
IFormatProvider cut = new System.Globalization.CultureInfo("en-US", true);

Or you can use the current culture which Is in the string Date by using current culture method as soon in following line.

 C# |  copy code |? 
IFormatProvider cut = System.Threading.Thread.CurrentThread.CurrentCulture; 

sample code for converting string to Datetime in Csharp.

 C# |  copy code |? 
string some_date="01/08/2012";
        DateTime data = Convert.ToDateTime(some_date);

Leave a Comment

Your email address will not be published.