John
John

Reputation: 487

Convert string to datetime in asp.net

this is my input to a text box from a datetime calendar and to store the datetime in the DB i want the value to be changed to Date time.

DateTime Res_date = Convert.ToDateTime(txt_RespondBy.Text); 

when I convert it gives a error saying string not recognised as valid date time. How to convert the input to date time..

value of txt_RespondBy.Text is : 10/27/2011 03:25

Upvotes: 1

Views: 14739

Answers (5)

Davide Piras
Davide Piras

Reputation: 44595

use DateTime.Parse, see MSDN: DateTime.Parse Method (String)

string[] dateStrings = {"2008-05-01T07:34:42-5:00", 
                        "2008-05-01 7:34:42Z", 
                        "Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
   DateTime convertedDate = DateTime.Parse(dateString);
   Console.WriteLine("Converted {0} to {1} time {2}.", 
                     dateString, 
                     convertedDate.Kind.ToString(), 
                     convertedDate);
}

There is Also ParseExact where you can specify the pattern string you are using....

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20638

Use DateTime.TryParseExact to avoid exceptions.

http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx

Upvotes: 2

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34641

What is the format of the string you're trying to parse? Anyway, take a look at DateTime.ParseExact(): http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

It allows you to provide a format in which the date is represented.

Upvotes: 1

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10965

You should use DateTime.Pares or DateTime.ParseExact

Upvotes: 1

Luke Girvin
Luke Girvin

Reputation: 13452

Use DateTime.ParseExact with the correct format string.

Upvotes: 1

Related Questions