本文介绍了我如何将文本框中的日期转换为sql server中的datetime formate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim())。ToString(); 抛出异常即 字符串未被识别为有效的DateTime。解决方案 我建​​议使用 DateTime.TryParse [ ^ ]方法而不是 Convert.ToDateTime 。 MSDN提到:(它)使用指定的特定于文化的格式信息和格式化样式将指定的日期和时间字符串表示形式转换为其DateTime等效项,并返回一个值,指示转换是否成功 。 问题在 Convert.ToDateTime(txtDateOfBirth.Text.Trim()) if你知道日期时间格式,尝试使用 DateTime.ParseExact 或 DateTime.TryParseExact DateTime dt = DateTime.ParseExact(txtDateOfBirth.Text.Trim(), MM / dd / yyyy, null ); // 如果日期格式为MM / dd / yyyy // 示例日期19/11/2014 你可以这样做: http://msdn.microsoft.com/en-us/library/ch92fbc1(v = vs.110).aspx [ ^ ] DateTime dateValue; if (DateTime.TryParse(txtDateOfBirth.Text.Trim(), out dateValue)) { employee.DateOfBirth = dateValue.ToString(); } 其他 { // 无法解析给定日期 } 但是,什么我不明白你解析一个字符串到目前为止,然后再将其转换为字符串。你可能想要考虑一下。 employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim()).ToString();throwing an exception ie,String was not recognized as a valid DateTime. 解决方案 I'd suggest to use DateTime.TryParse[^] method instead of Convert.ToDateTime. MSDN mention: "(it) converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded".issue is in Convert.ToDateTime(txtDateOfBirth.Text.Trim())if you know the date time format, try with DateTime.ParseExact or DateTime.TryParseExactDateTime dt = DateTime.ParseExact(txtDateOfBirth.Text.Trim(), "MM/dd/yyyy", null);//if the date format is MM/dd/yyyy // sample date 19/11/2014You could do something like this:http://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx[^]DateTime dateValue;if (DateTime.TryParse(txtDateOfBirth.Text.Trim(), out dateValue)){ employee.DateOfBirth = dateValue.ToString();}else{ //Can not parse the given date}However, what I do not understand that you parse a string to date and then convert it again to string. You might want to think about it. 这篇关于我如何将文本框中的日期转换为sql server中的datetime formate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-03 02:08