String was not recognized as a valid DateTime during insert

白昼怎懂夜的黑 提交于 2019-12-02 07:38:31

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.
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);

Try using DateTime.ParseExact.

DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!