山本一樹
山本一樹

Reputation: 157

Converting string to datetime is returning the min value

I am using Visual Studio and I want to convert the string I have in my textbox into the DateTime format. I am using the function Convert.ToDateTime() but the value that is returned is the min value (0/0/0001 00:00:00).

What is the problem?

The code where I retrieve the string from my textbox.

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

The code where I convert the string to datetime format.

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

Upvotes: 2

Views: 2164

Answers (2)

Lucas Lim
Lucas Lim

Reputation: 515

use try parse, it'll return false if any conversion error occurs

Datetime @dateTime;

if(DateTime.TryParse(txtStartDate.Text, out @dateTime)) {
    return @dateTime;
}

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98840

As pointed in my comment, Convert.ToDateTime method returns DateTime.MinValue if the parameter is 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.

Probably your parameter is null but since you didn't gave us more details, we can't know what the exact problem is.

As a comman mistake, make sure that you are passing as a parameter .Text property of your TextBox, not itself. See Squid's comment.

Upvotes: 3

Related Questions