帮助一个字符串日期转换为DateTime [英] Help converting a string date to a DateTime

查看:193
本文介绍了帮助一个字符串日期转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是与一个提交按钮一个文本框Ajax控件工具包日历扩展。简单的。

调试器显示文本正确被转移到呼叫方法,但此行转换code的文本框的文本转换为1/1/0001 12:00:00 AM。文本框日期是这样的:2011/4/15

 的DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);

我在做什么错了?


解决方案

您应该使用的 DateTime.Parse()方法

 的DateTime txtMyDate = DateTime.Parse(txtDate.Text);

如前所述,你也可以使用的 DateTime.ParseExact()使用类似的语法如下所示:

 的DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
                                         [字符串格式]
                                         [提供商的IFormatProvider]);

解析VS ParseExact:

解析() - 假定数据是有效的,并会尽力把它融入型,迫使事情,似乎当开发人员有机会来调用常识依稀可笑的。

ParseExact() - 只允许指定的确切格式和将抛出的任何变化

源的解析VS 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.

Source on Parse vs ParseExact

这篇关于帮助一个字符串日期转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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