简体   繁体   English

错误:在C#4中无法将字符串识别为有效的DateTime(格式)

[英]Error :String was not recognized as a valid DateTime (Formating) in C# 4

I have a datepicker in my c# application that provide strings like these: 我的c#应用程序中有一个datepicker,它提供如下字符串:

"2016/1/1" “ 2016/1/1”

"2016/11/15" “ 2016/11/15”

But I want to change them to these formats: 但我想将它们更改为以下格式:

"2016/01/01" “ 2016/01/01”

"2016/11/15" “ 2016/11/15”

I use this code: 我使用以下代码:

    string searchstring = " and ProductStartDate Between '" + 
    String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(calender_from.Text)) + 
    "' and '" + 
    String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(calender_to.Text)) + "'";

but when I run following error occurs : 但是当我运行以下错误发生:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll mscorlib.dll中发生了'System.FormatException'类型的未处理异常

Additional information: String was not recognized as a valid DateTime. 附加信息:字符串未被识别为有效的DateTime。

Any idea? 任何想法?

Use DateTime.ParseExact instead of Convert.ToDateTime : 使用DateTime.ParseExact而不是Convert.ToDateTime

calender_from.Text = "2016/1/1";

DateTime date = DateTime.ParseExact(calender_from.Text, "yyyy/M/d", null);

Then you can do this: 然后,您可以执行以下操作:

string searchstring = " and ProductStartDate Between '" + String.Format("{0:yyyy/MM/dd}", date) + ...

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

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