0

I'm trying to convert a string to DateTime and then insert it to sql. In my local computer all works fine, but on the server the application throws an exception:

String was not recognized as a valid DateTime 

I use Textboxs to create a datetime object like this:

enter image description here

I'm using this line to build the date:

start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue; end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue; 

and then convert it

This is the code after the button click:

 act_event add_event = new act_event(); string start, end; DateTime strt_date = new DateTime(); DateTime end_date = new DateTime(); add_event.name = name_event.Text; start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue; end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue; strt_date = Convert.ToDateTime(start); //This is the line that throws the error add_event.start = strt_date; end_date = Convert.ToDateTime(end); add_event.end = end_date; add_event.description = des_event.Text; add_event.address = loc_event.Text; db.add_event(add_event); 

Then I get this:

enter image description here

1
  • 1
    And this is why you use date pickers instead of text... Commented Jul 30, 2013 at 17:15

2 Answers 2

2

The problem you are having most likely links to formatting issues. Since DateTime has a lot of different ways it can be formatted, the Convert.ToDateTime( ... ) is probably using a format that is different from your hour\minute format.

Try using DateTime.Parse \ DateTime.TryParse \ DateTime.ParseExact

See:

See Custom Date and Time Format Strings for formatting strings

Sign up to request clarification or add additional context in comments.

5 Comments

I just can't convert the datepicker text to Datetime, no matter if I use ConvertTo, Parse, ParseExact. it just throws error. That's annoying : \
What is the string text from the datepicker?
You can see it in the picture above
The string 31/07/2013 is parsed by DateTime sample = DateTime.ParseExact("31/07/2013", "dd/MM/yyyy", null); on my environment
DateTime sample = DateTime.ParseExact("31/07/2013 8:15", "dd/MM/yyyy h:m", null); also works
0
  1. It's probably a formatting\localization issue, different machines may be set to different locales and expect the dates to written differently.

  2. I think you're getting yourself into unneeded trouble. Why create the string in the first place only to parse it later? Wouldn't it be easier to do something like -

    date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

with the data from the controls?

1 Comment

I just can't convert the datepicker text to Datetime, no matter if I use ConvertTo, Parse, ParseExact. it just throws error. That's annoying : \

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.