问题描述
我使用的是与一个提交按钮一个文本框Ajax控件工具包日历扩展。简单的。
调试器显示文本正确被转移到呼叫方法,但此行转换code的文本框的文本转换为1/1/0001 12:00:00 AM。文本框日期是这样的:2011/4/15
的DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);
我在做什么错了?
您应该使用的:
的DateTime txtMyDate = DateTime.Parse(txtDate.Text);
如前所述,你也可以使用的使用类似的语法如下所示:
的DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
[字符串格式]
[提供商的IFormatProvider]);
解析VS ParseExact:
解析() - 假定数据是有效的,并会尽力把它融入型,迫使事情,似乎当开发人员有机会来调用常识依稀可笑的。
ParseExact() - 只允许指定的确切格式和将抛出的任何变化
。
I'm using the Ajax control toolkit calendar extender on a textbox with a submit button. Simple.
The debugger shows that the text is properly being transferred to calling method, but this line of conversion code converts textbox text to 1/1/0001 12:00:00 AM. The text box date is this: 4/15/2011
DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);
What am I doing wrong?
You should use the DateTime.Parse() method:
DateTime txtMyDate = DateTime.Parse(txtDate.Text);
As mentioned you can also use DateTime.ParseExact() using a similar syntax as shown:
DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
[string format],
[IFormatProvider provider]);
Parse vs ParseExact:
Parse() - assumes the data is valid and does its best to fit it into the type, forcing things that seem vaguely ridiculous when a developer has a chance to invoke common sense.
ParseExact() - only allows the exact format specified and will throw on any variation.
这篇关于帮助一个字符串日期转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!