Click here to Skip to main content
15,846,521 members
Please Sign up or sign in to vote.
5.00/5 (10 votes)
See more:
Hi all
"String was not recognized as a valid DateTime."


I am getting the above exception in my website.I Don't know why this type of error is coming!

I searched in google and find that use ParseExact rather than Parse to convert the date time .By in my Project I haven't used Parse .

Always I use Convert.ToDateTime() and once i have used TryParse()

Where the exception is actually coming and why ??

Please suggest me.

Thanks in advance
Posted
Updated 28-Jan-19 3:59am
v2
Comments
hitech_s 4-Jun-12 6:47am    
if the string contains no data then also you will get the same error error while converting to dataetime
kodeLogic 4-Jun-12 7:00am    
May date month or year are in the wrong position..
Andreas Gieriet 4-Jun-12 7:16am    
What text do you have where the execption is thrown?
Can you show that offending "date" text, so that we might help further on the issue.
Cheers
Andi
leonelbeira 22-Aug-12 19:00pm    
Hi , i lost time and time traing to resolve datetime parsing,
when i found one soluction that solve my problem.

Before you must have control in which culture you are running, and off course if you want Portugues- pt-PT and english en-EN,

I have override my cultureInfo so i can run in any format date, and i will never get this kind of error:


protected override void InitializeCulture()
{
CultureInfo CI = new CultureInfo("pt-PT");
CI.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";

Thread.CurrentThread.CurrentCulture = CI;
Thread.CurrentThread.CurrentUICulture = CI;
base.InitializeCulture();
}

or you can read the format date from any source.
Hope this helps.
Mac12334 24-Aug-12 3:35am    
Thanks for giving valuable information.

The error shown in question might have been thrown by Convert.ToDateTime method as shown below:
C#
string dateString = @"20/05/2012";
//The following code throws
//FormatException: String was not recognized as a valid DateTime
DateTime date = Convert.ToDateTime(dateString);

In the above code the dateString represents Date in the Day/Month/Year format.
By default the en-US culture is used by .NET according to which the Date is in Month/Day/Year format. So, when ToDateTime method is used it throws error as 20 is out of Month range.

To avoid this error the appropriate culture can be used as follows
C#
string dateString = @"20/05/2012";
DateTime date2 = Convert.ToDateTime(dateString,
	System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);

Or the ParseExact method can be used with the required custom format as shown below:
C#
string dateString = @"20/05/2012";
DateTime date3 = DateTime.ParseExact(dateString, @"d/M/yyyy", 
	System.Globalization.CultureInfo.InvariantCulture);

Here d/M/yyyy matches both single and double digit months, days like 20/05/2012, 20/5/2012. The custom format is used in conjunction with InvariantCulture.

When TryParse method is used as shown below
C#
DateTime date4;
string dateString = @"20/05/2012";
bool result = DateTime.TryParse(dateString,out date4);

the parsing fails, but it will not throw error, rather it returns false indicating that the parsing failed.
 
Share this answer
 
Comments
Shahin Khorshidnia 4-Jun-12 13:23pm    
Good answer.
Thanks7872 4-Oct-13 7:12am    
Too late....+5..!
VJ Reddy 4-Jun-12 13:32pm    
Thank you, Shahin :)
Devendra Kumar 6-Mar-14 23:59pm    
Superb thanks saved my one day :)
Manas Bhardwaj 4-Jun-12 15:37pm    
very well explained +5
Hi,
You have to take care while doing the conversion to datetime. It can throw error depending on the datetime format of your system.So its better to use the following always,

DateTime date= new DateTime(YourDateTime.Now.Year, YourDateTime.Now.Month, YourDateTime.Now.Day, 0, 0, 0, 0);

Happy Coding :)
 
Share this answer
 
v2
Comments
Mac12334 4-Jun-12 7:15am    
Thanks For reply
One Query
Can you please say me why the Exception is coming ??
Is it coming due to the Convert.ToDateTime or due to the TryParse???
Andreas Gieriet 4-Jun-12 7:50am    
Local time or UTC?
Cheers
Andi
Linto Leo Tom 4-Jun-12 9:57am    
Due to Convert.ToDateTime
Meher Khan 15-May-14 13:00pm    
great bro.. this give me a great result as i want +1
Linto Leo Tom 15-May-14 14:13pm    
:)
Dates are the most locale-specific things of all. :)
So, check if the thread locale used on server side when you parse the string is matching the format of the date entered. You should require a specific format, validate the datetime string on client and server side and process the string under a locale that matches the required format or parse it manually using string or regexp tools and create the datetime instance yourself with these elements as parameter.

It would be good if you would provide a sample of date string as you expect it to be entered.
 
Share this answer
 
v2
it was better that we see your code, but your system have culture, and if you don't want to set it with system culture, change the culture at runtime
for example in converting string you can tell the system not to use its default culture.
 
Share this answer
 
Comments
Shahin Khorshidnia 4-Jun-12 13:24pm    
I could be a good answer if there was a sample code beside. I don't know who voted 1 and who voted 5! But my Vote is 3 (Maybe revote after impoving the solution ;) )
Hello,

In you case try to avoid fill date from user instand of that use calendar control for date.
XML
Note:
When ever date and time is concern you should always follow your database sever format.
 
Share this answer
 
v2
Comments
Mac12334 4-Jun-12 6:40am    
Thanks For reply
One Query
Can you please say me why the Exception is coming ??
Is it coming due to the Convert.ToDateTime or due to the TryParse???
Andreas Gieriet 4-Jun-12 7:15am    
Run in debugger and set the exception thrown check mark.
How do you get the exception? And stack trace? If yes, look there.
Cheers
Andi
Andreas Gieriet 4-Jun-12 7:36am    
See Convert.ToDateTime Method for description what exceptions get thrown: this may throw FormatException: "value is not a properly formatted date and time string".

While DateTime.TryParse tells what exceptions may be thrown there. It may throw

ArgumentOutOfRangeException: "The date is in Japanese Emperor Year (Wareki) format and the year is out of range".

The overload of DateTime.TryParse may throw three different kind of exceptions:

ArgumentException ("styles is not a valid DateTimeStyles value" or "styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).")

ArgumentOutOfRangeException ("The date is in Japanese Emperor Year (Wareki) format and the year is out of range.")

NotSupportedException ("provider is a neutral culture and cannot be used in a parsing operation.")

So, what is not clear from these descriptions? Which method do you call and what actual argument values do you pass to it? It should be farly easy to detect the problem (maybe not so easy to solve, though...).

Cheers
Andi
 
Share this answer
 
after spending a lots of time i solve this way.


string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
 
Share this answer
 

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