String was not recognized as a valid DateTime during insert

折月煮酒 提交于 2019-12-02 16:13:00

问题


I get the following error when i try to convert to date time.

String was not recognized as a valid DateTime.

 cost.b_date = DateTime.Parse(c_date.Text) ;//c_date.Text = 12/28/2012

Then i try

    string date = string.Format("{0:yyyy-MM-dd}",c_date.Text);
    cost.b_date = DateTime.Parse(date) ;

but i get the same exception how to fix this problem.


回答1:


Using string.Format when the input is a string is pointless.

If you know the format of the string, you should use DateTime.ParseExact or DateTime.TryParseExact. For example, for the string you've got, you could use:

DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
                                    CultureInfo.InvariantCulture);

You should consider:

  • Is this user input? If so, use TryParseExact to detect user error more easily without an exception.
  • Do you definitely know the exact format? If not, using DateTime.TryParse may be more appropriate.
  • Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
  • Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a DateTime to start with, that would be preferable.



回答2:


CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);



回答3:


Try using DateTime.ParseExact.

DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);


来源:https://stackoverflow.com/questions/14089917/string-was-not-recognized-as-a-valid-datetime-during-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!