1

IDE: VS 2010, c# .net

I m having a textbox1 which is containg date

i.e

textbox1.text = "16/04/2014"  

And I am having a datetime object

Datetime dt ;
dt = DateTime.Parse(textbox1.text);
//trying to set date in dt from the textbox1.text value

but it is returning String was not recognized as a valid DateTime. error.

pls tell the correct way.

user3410150
  • 61
  • 1
  • 2
  • 8
  • That string seems to be in this format dd/MM/yyyy, if your locale settings are different then you get that error. – Steve Apr 16 '14 at 07:47

3 Answers3

1

This should do the trick in your format:

DateTime dt = Convert.ToDateTime(textbox1.text);

You can read more about it here.

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
0

You will need to specify the format your string is in, to get it parsed correctly.

You can use DateTime.ParseExact.

See this answer for more information: Have a look at this answer: datetime.parse and making it work with a specific format

Use

DateTime.ParseExact((textbox1.Text, "dd/MM/yyyy", null);
Community
  • 1
  • 1
Dr.Elch
  • 2,105
  • 2
  • 17
  • 23
0

You can use like this :

string format = "dd/MM/yyyy";

DateTime dateTime = DateTime.ParseExact(textbox1.text, format,
        CultureInfo.InvariantCulture);
Seçkin Durgay
  • 2,758
  • 4
  • 27
  • 36