当我运行错误时出现字符串未被识别的有效日期时间 [英] when i run error appears string was not recognized valid date time

查看:102
本文介绍了当我运行错误时出现字符串未被识别的有效日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DateTime dateofbirth = Convert.ToDateTime(txt_DOB.Text);
  DateTime Weddingday  = Convert.ToDateTime(txt_wedding.Text);

    if (dateofbirth.Year !=1900)
    SendSMS(txt_DOB.Text.Trim());
    else
   if (Weddingday.Year != 1900)
   SendSMS(txt_wedding.Text.Trim());







运行此代码错误显示字符串未被识别为有效日期时间;



来自我的上述代码有什么错误或错误或问题。请找出&帮助我。



Rgds,

narasiman P

谢谢,

代码项目。




run this code error shows "String Was Not Recognized a Valid Date Time";

from my above code what is the mistake or error or problem.please find out & help me.

Rgds,
narasiman P
Thanks,
Code Project.

推荐答案

如果您使用Convert.ToDateTime,它会尝试使用运行代码的计算机的文化设置来解析输入字符串。如果用户输入的字符串不是该格式(例如,用户输入2012年12月29日并且您的文化设置为美国并且预期12/29/2012)那么您将获得例外。如果用户输入无效日期,例如sdfs / wewe / 22334,您将遇到同样的问题



有两种解决方案:使用 TryParseExact [ ^ ]并报告问题或用户,或者阻止用户使用a输入错误的日期 DateTimePicker [ ^ ]。



就个人而言,我更喜欢防止出现问题,同时向用户提供更好的输入法,所以我尽可能使用DateTimePicker。
hen you use Convert.ToDateTime, it tries to parse the input string using the Culture settings of the computer that your code is running on. If the string input by the user is not in that format (for example, the user enters "29 Dec 2012" and your Culture is set to US and expects "12/29/2012") then you will get an exception. You will get the same problem if the user enters an invalid date such as "sdfs/wewe/22334"

There are two solutions: use TryParseExact[^] instead, and report the problem or the user, or prevent the user from entering a wrong date altogether by using a DateTimePicker[^] instead.

Personally, I prefer to prevent problems, and present the user with a "nicer" input method at the same time, so I use a DateTimePicker whenever possible.


这篇关于当我运行错误时出现字符串未被识别的有效日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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