2

我正在使用 Visual Studio,我想将文本框中的字符串转换为DateTime格式。我正在使用该函数Convert.ToDateTime(),但返回的值是最小值 ( 0/0/0001 00:00:00)。

问题是什么?

我从文本框中检索字符串的代码。

//pass startdate end date to studentResult.aspx
Session["startdate"] = txtStartDate.Text.ToString();
Session["enddate"] = txtEndDate.Text.ToString();

我将字符串转换为日期时间格式的代码。

string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
DateTime one = Convert.ToDateTime(startdate);
DateTime two = Convert.ToDateTime(enddate);
4

2 回答 2

3

正如我的评论中所指出的,如果参数是,Convert.ToDateTime方法返回。DateTime.MinValuenull

Return Value
Type: System.DateTime
The date and time equivalent of the value of value, or the date and time equivalent of DateTime.MinValue if value is null.

可能您的参数是null,但是由于您没有向我们提供更多详细信息,因此我们无法知道确切的问题是什么。

作为一个 comman 错误,请确保您是作为参数.Text属性传递的TextBox,而不是本身。请参阅 Squid 的评论

于 2013-07-09T05:34:07.060 回答
0

使用 try parse,如果发生任何转换错误,它将返回 false

Datetime @dateTime;

if(DateTime.TryParse(txtStartDate.Text, out @dateTime)) {
    return @dateTime;
}
于 2013-07-09T07:23:24.127 回答