字符串未被识别为有效的DateTime。在C#中 [英] String was not recognized as a valid DateTime. in C#

查看:139
本文介绍了字符串未被识别为有效的DateTime。在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串未被识别为有效的DateTime。在C#

我的约会是



String was not recognized as a valid DateTime. in C#
my datesting is

lblStartDate.Text=4/16/2014 12:00:00:AM;





i试过这个





i tried this

DateTime dtstring1 = DateTime.ParseExact(lblStartDate.Text, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
dtStartDate = Convert.ToDateTime(dtstring1.ToString("dd/MM/yyyy"));            





建议我获得解决方案



提前致谢。



Suggest me to get a solution

Thanks in advance.

推荐答案

Quote:

lblStartDate.Text = 4/16/2014 12:00 :00:AM;

lblStartDate.Text=4/16/2014 12:00:00:AM;



AM之前有一个假结肠(':'指示符。


There's a spurious colon (':') before the AM designator.


为什么?

为什么要将用户字符串转换为DateTime,然后将其转换为字符串,以便转换它又回到了DateTime吗?



您得到的错误可能在第二行,因为您指定了要转换的字符串的确切格式DateTime to,但是将ToDateTime转换为使用标准的系统范围日期格式 - 所以如果它们不匹配则会出错。



看起来像什么你要做的是从用户那里读取一个DateTime,然后扔掉时间部分 - 这不是n根本不需要任何字符串转换:

Why?
Why are you converting a user string to a DateTime, then converting that to a string, in order to convert it right back to a DateTime again?

The error you are getting is probably in the second line, because you are specifying the exact format of the string you are converting the DateTime to, but leaving the ToDateTime conversion to use teh standard system wide date format - so if they don't match you will get an error.

What it looks like you are trying to do is read a DateTime from the user, then throw away the time part - which doesn't need any string conversions at all:
DateTime dtstring1 = DateTime.ParseExact(lblStartDate.Text, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
dtStartDate = dtstring1.Today;

会这样做。


试试这个



try this

DateTime varDate;
varDate.ToString("yyyy-MM-dd h:mm:ss tt")





ToString,可以指定日期模式。



ToString, one can specify the date pattern.


这篇关于字符串未被识别为有效的DateTime。在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆