c# - 将字符串转换为日期时间返回最小值

标签 c# string datetime

我正在使用 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);

最佳答案

正如我的 comment 中所指出的, Convert.ToDateTime方法返回 DateTime.MinValue如果参数为null

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,但由于您没有向我们提供更多详细信息,因此我们无法知道确切的问题是什么。

作为一个常见错误,请确保您将 TextBox.Text 属性作为参数传递,而不是其本身。参见鱿鱼的comment .

关于c# - 将字符串转换为日期时间返回最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17540542/

相关文章:

mysql - SQL 查询只排除最近 24 小时的数据?

java - FullName Timezone 的时间不正确

c# - HTTP 错误 414。请求 URL 太长。网站

c# - 使用 .NET 遍历列表以添加元素

c# - 网页倒计时器和自动提交

c++ - 将用户输入的前两个单词按一个空格拆分,然后存储剩余的短语(C++)

arrays - 检查列表字符串中的元素是否为 BigQuery

c# - 为什么我在用户 "Server"垃圾回收时会出现内存泄漏?

swift - 检查字符串是 int 还是 double ,在 swift 3 中有扩展

mysql - 在日期/时间范围之间选择数据