Abbas
Abbas

Reputation: 5044

how to convert string to datetime in .net

hey guys, i have a datetime in string format and now i want to convert the same in datetime format, in the string i have following string.... (12.01.2011) dd.mm.yyyy format, now i want this format to be converted in datetime format because i want to store this in database which has a field whose datatype is datetime....

Please reply as soon as possible. Thanks and regards Abbas electricwala.

Upvotes: 0

Views: 686

Answers (3)

Grastveit
Grastveit

Reputation: 16150

As you have an exact dateformat you don't need to worry about regional settings:

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

Or with error-checking:

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

Upvotes: 0

Morten
Morten

Reputation: 3844

Use DateTime.Parse and be aware of the regional settings. You can bypass regional settings by providing your own CultureInfo. I don't know which language you use, but my language (danish) support your 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 string, and construct a new Date.

Regards, Morten

Upvotes: 1

John xyz
John xyz

Reputation: 186

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

Upvotes: 1

Related Questions