简体   繁体   English

转换为DateTime时,字符串未被识别为有效的DateTime

[英]String was not recognized as a valid DateTime when converting to DateTime

I'm trying to convert a string to DateTime and then insert it to sql. 我正在尝试将字符串转换为DateTime,然后将其插入到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: 我使用Textboxs来创建一个这样的日期时间对象:

在此输入图像描述

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. 由于DateTime有许多不同的格式化方式,因此Convert.ToDateTime( ... )可能使用的格式与hour\\minute格式不同。

Try using DateTime.Parse \\ DateTime.TryParse \\ DateTime.ParseExact 尝试使用DateTime.Parse \\ DateTime.TryParse \\ DateTime.ParseExact

See: 看到:

See Custom Date and Time Format Strings for formatting strings 请参阅自定义日期和时间格式字符串以格式化字符串

  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); date = new DateTime(date.year,date.month,date.day,HH,MM,SS);

with the data from the controls? 与控件的数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM