[英]String was not recognized as a valid DateTime(System.FormatException)?
I am getting error as: 我收到以下错误消息:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
mscorlib.dll中发生类型'System.FormatException'的异常,但未在用户代码中处理
Additional information: String was not recognized as a valid DateTime.
附加信息:字符串未被识别为有效的DateTime。
This is my code : 这是我的代码:
if (txtRefDate.Text != "")
{
string[] splitdate = txtRefDate.Text.Split('-');
string newdate = splitdate[1] + "-" + splitdate[0] + "-" + splitdate[2];
DateTime Compdate = Convert.ToDateTime(newdate);//On this line i'm getting error
string date = Compdate.ToString("yyyy-MM-dd");
obj.RefrenceDate = Convert.ToDateTime(date);
}
I am using CalenderExtender
on my textbox
. 我在
textbox
上使用CalenderExtender
。 I tried Parse
and ParseExact
, but it is not working. 我尝试了
Parse
和ParseExact
,但是它不起作用。 What am I doing wrong here? 我在这里做错了什么?
DateTime Compdate;
if (!String.IsNullOrEmpty(txtRefDate.Text) && DateTime.TryParse(txtRefDate.Text, out Compdate))
{
obj.RefrenceDate = Compdate.Date;
}
Also take a look at TryParseExact()
, which allows you to supply more info about the expected format of your input. 还请看一下
TryParseExact()
,它使您可以提供有关输入的预期格式的更多信息。
And if this fails, start logging the string values that fail. 如果失败,则开始记录失败的字符串值。 We need to see examples of what didn't work.
我们需要查看不起作用的示例。
Hmm you seem to be doing a lot of unnecessary steps to parse and set a DateTime
嗯,您似乎在执行许多不必要的步骤来解析和设置
DateTime
var textDate = "06-20-2018";
if (!string.IsNullOrEmpty(textDate))
{
var parsedDate = DateTime.ParseExact(textDate, "MM-dd-yyyy", null);
obj.RefrenceDate = parsedDate;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.