字符串不是有效的日期格式 [英] String is not a valid date format

查看:201
本文介绍了字符串不是有效的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有



我试图通过带有以下代码但面临错误的文本框输入dd-mm-yyyy格式的日期。请告诉我如何解决这个问题。



DateTime dt = Convert.ToDateTime(txtDDate.Text);

string s2 = dt。 ToString(dd-MM-yyyy);

DateTime deliveryDt = Convert.ToDateTime(s2);





问候

解决方案

我开始输入一个冗长的回复,但后来记住了我的解决方案 - 如何将字符串转换为日期时间 [ ^ ]。另请注意Richard Deeming关于TryParseExact的评论


此代码



  string  s2 = dt.ToString(  dd-MM-yyyy); 
DateTime deliveryDt = Convert.ToDateTime(s2);





毫无意义。它不起作用的原因是因为当你说Convert.ToDateTime时,它希望字符串格式为操作系统的日期格式。如果您的操作系统未设置为dd-MM-yyyy,则转换将失败。更糟糕的是,如果您的操作系统*被设置为,但是您将代码移动到具有不同设置的机器(如网络主机)怎么办?



如果它*做了*工作,deliveryDt将与dt相同。您将1月2015转换为字符串然后再转换为日期,您有什么? 2015年1月1日,你还没有做任何事情。我假设您的代码来自于错误的信念,即日期某种程度上带有内部格式,但它们没有。日期是日期,它们代表一个时间点。当你转换为字符串时,它们只有一种格式。



将日期保留为DateTime,直到你需要显示它们,然后才将它们转换为你选择的字符串格式。


Dear All

I am trying to input date in dd-mm-yyyy format through a text box with following code but facing the error. Please tell me how to resolve the issue.

DateTime dt = Convert.ToDateTime(txtDDate.Text);
string s2 = dt.ToString("dd-MM-yyyy");
DateTime deliveryDt = Convert.ToDateTime(s2);


Regards

解决方案

I started typing a longish response but then remembered my solution here - how to convert string to datetime[^]. Note also the comment about TryParseExact from Richard Deeming


This code

string s2 = dt.ToString("dd-MM-yyyy");
DateTime deliveryDt = Convert.ToDateTime(s2);



is pointless. The reason it isn't working is because when you say Convert.ToDateTime it expects the string to be in the format as the operating system's date format. If your OS is not set to "dd-MM-yyyy" then the conversion will fail. Worse still, what if your OS *is* set to that, but you move the code to a machine that has a different setting like a web host?

If it *did* work, deliveryDt would be the same as dt. You convert 1 jan 2015 to a string then back to a date, what do you have? 1 jan 2015, you haven't done anything. I am assuming you code comes from the mistaken belief that dates somehow carry an internal format, but they don't. Dates are dates, they represent a point in time. They only have a format when you convert then to string.

Keep dates as DateTime until you need to display them, and only then convert them to a string of your chosen format.


这篇关于字符串不是有效的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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