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:
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:
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
It's probably a formatting\\localization issue, different machines may be set to different locales and expect the dates to written differently.
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.