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

Dvirski
  • 321
  • 4
  • 16
  • 36

2 Answers2

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

Community
  • 1
  • 1
jrbeverly
  • 1,611
  • 14
  • 20
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?

Vadim
  • 2,847
  • 15
  • 18
  • 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 : \ – Dvirski Jul 30 '13 at 17:54