繁体   English   中英

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

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

我的c#应用程序中有一个datepicker,它提供如下字符串:

“ 2016/1/1”

“ 2016/11/15”

但我想将它们更改为以下格式:

“ 2016/01/01”

“ 2016/11/15”

我使用以下代码:

    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)) + "'";

但是当我运行以下错误发生:

mscorlib.dll中发生了'System.FormatException'类型的未处理异常

附加信息:字符串未被识别为有效的DateTime。

任何想法?

使用DateTime.ParseExact而不是Convert.ToDateTime

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

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

然后,您可以执行以下操作:

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