Click here to Skip to main content
15,797,721 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
 String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:


Line 132:        protected void Button4_Click(object sender, EventArgs e)
Line 133:        {
Line 134:            DateTime a = Convert.ToDateTime(TextBox13.Text);
Line 135:            DateTime b = Convert.ToDateTime(TextBox14.Text);
Line 136:            string c = (b - a).TotalDays.ToString();


What I have tried:

DateTime a = Convert.ToDateTime(TextBox13.Text);
DateTime b = Convert.ToDateTime(TextBox14.Text);
string c = (b - a).TotalDays.ToString();
TextBox15.Text = c.ToString();
Posted
Updated 18-Mar-16 1:39am

TryParse or ParseExact should be used. Follow this awesome answer - String was not recognized as a valid DateTime.[^]
 
Share this answer
 
C#
string c = (b - a).TotalDays.ToString();

Statements like that are not very useful when you are not sure of what is happening. Use proper intermediate types so you can step through the code with your debugger and see the results at each stage. Something like:
C#
TimeSpan c = b - a;
int days = c.TotalDays;
string str = days.ToString();
 
Share this answer
 
Comments
Member 12398028 18-Mar-16 13:41pm    
Using the 'int' datatype creates the error
[implicit convert type 'double' to 'int'.An Explicit conversion exists]

TimeSpan c = b - a;
double days = c.TotalDays;
string str = days.ToString();
Richard MacCutchan 18-Mar-16 14:03pm    
My apology, the Days field is an integer type.
First you Converted the values to datetime, then just substract it and return it in Timespan
C#
DateTime a = Convert.ToDateTime(TextBox13.Text);
DateTime b = Convert.ToDateTime(TextBox14.Text);
TimeSpan ts1 = b.Subtract(a);

</pre>
Hope it gives you the exact result..
 
Share this answer
 
v3
Comments
phil.o 18-Mar-16 7:15am    
Using Convert method to get a DateTime from a string is a bad practice. As suggested by Tadit Dash, Parse and/or TryParse methods should be used.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900