How to convert string to datetime in .net

Hey guys, I have datetime in string format, and now I want to convert the same in datetime format, in the line I have the following line .... (12.01.2011) Format dd.mm.yyyy, now I want so that this format is converted to datetime format, because I want to save it in a database that has a field whose datatype is datetime ....

Please reply as soon as possible. Thank you and welcome Abbas electricwala.

0
source share
3 answers

Use DateTime.Parse and know the regional settings. You can get around regional settings by providing your own CultureInfo. I do not know which language you are using, but my language (Danish) supports the date format (dd.mm.yyyy). Thus, I use the following syntax:

        string inputDate = "31.12.2001";
        CultureInfo cultureInfo =  new CultureInfo("da-DK");

        DateTime parsedDate = DateTime.Parse(inputDate, cultureInfo);

Alternatively, you can split the input line and build a new date.

Regards, Morten

+1
source

See the DateTime.Parse function in msdn: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

+1
source

, :

DateTime.ParseExact(inputDate , "dd.MM.yyyy", null)

:

DateTime value;
if (DateTime.TryParseExact(inputDate , "dd.MM.yyyy", null, 
    DateTimeStyles.None, out value))
{
   // use value
}
0

All Articles