Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Error is" String is not a valid datetime string" [ error occurs at following code: DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null); ]



DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null);
Convert.ToDateTime(date).ToShortDateString();
Posted
Updated 14-Jan-13 21:22pm
v2
Comments
OriginalGriff 15-Jan-13 2:54am    
What do you mean "does not work some time?" What does it do when it "doesn't work"?
varun150 15-Jan-13 3:05am    
when i post date from the text box to database it gives an error i.e. string was not a valid datetime object something like this i don't remember it exactly.
but i refresh the page and post the same date again it shows no error
varun150 15-Jan-13 3:10am    
error occurs at following code:
DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null);
Sergey Alexandrovich Kryukov 15-Jan-13 2:55am    
No, please provide exact steps how to reproduce the problem.
—SA
varun150 15-Jan-13 3:14am    
there's no exact step i think this error occurs sometime only,
[
when i post date from the text box to database it gives an error i.e. string was not a valid datetime object something like this i don't remember it exactly.
but i refresh the page and post the same date again it shows no error
]

1 solution

I think you are a little confused - the second line of your code doesn't do anything:
C#
DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null);
Convert.ToDateTime(date).ToShortDateString();

But it is important to note that ToShortDateString does not return a specific, fixed format - particularly it does not return a string which is suitable for use with SQL. It returns a string which is dependant on the Culture that is set in teh machine, where SQL prefers to get 'yyyy-MM-dd' format dates if you hand them through as a string.
So two things:
First, hand your date through to SQL as a DateTime via a parametrized query (you should be using these at all times anyway to prevent an SQL injection attack which can accidentally or deliberately destroy your database). Don't convert dates to streings unless it s for presentation to the user!

Second, use TryParseExact instead - it reports a problem and allows you to log it and look at why it happened in better detail as well as report the problem to the user.

I'm wondering if the problem is to do with the DateTime format set on the Client machine - are you sure the date is in dd/MM/yyyy format? Have you checked?
 
Share this answer
 
Comments
varun150 15-Jan-13 3:35am    
thank you so much
OriginalGriff 15-Jan-13 3:49am    
You 're welcome!

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