1

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

John
  • 467
  • 7
  • 17
  • 27

5 Answers5

2

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....

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
2

Use DateTime.TryParseExact to avoid exceptions.

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

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
1

Use DateTime.ParseExact with the correct format string.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
1

You should use DateTime.Pares or DateTime.ParseExact

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
1

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.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67