Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET
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 4-Jun-12 1:19am
Mac123341.1K
Edited 4-Jun-12 5:56am
Nikfazan11.5K
v2
Comments
hitech_s at 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 at 4-Jun-12 7:00am
   
May date month or year are in the wrong position..
Andreas Gieriet at 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 at 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.
MAC123456 at 24-Aug-12 3:35am
   
Thanks for giving valuable information.
lmcuong at 6-Nov-12 2:56am
   
Thank you!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

The error shown in question might have been thrown by Convert.ToDateTime method as shown below:
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
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:
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
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.
  Permalink  
Comments
Shahin Khorshidnia at 4-Jun-12 13:23pm
   
Good answer.
Rohan Leuva at 4-Oct-13 7:12am
   
Too late....+5..!
VJ Reddy at 4-Jun-12 13:32pm
   
Thank you, Shahin :)
Devendra Kumar at 6-Mar-14 23:59pm
   
Superb thanks saved my one day :)
Manas Bhardwaj at 4-Jun-12 15:37pm
   
very well explained +5
VJ Reddy at 4-Jun-12 19:41pm
   
Thank you, Manas :)
Abhinav S at 4-Jun-12 22:12pm
   
Perfect answer. 5.
VJ Reddy at 4-Jun-12 22:36pm
   
Thank you, Abhinav :)
Maria De Freitas at 5-Dec-12 8:52am
   
Thank you!!!
Raju Hasan at 8-Jan-13 8:10am
   
I get Date from Date Picker which come with jquery;
In my database RegDate is Date formate & in my class regDate is DateTime Format.
When i want to save data into database then i face "String was not recognized as a valid DateTime."
MY CODE IS
string datestring = registrationDateTextBox.Text;
aStudent.RegDate = Convert.ToDateTime(datestring, System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
PLZ help me......
npsrajan at 19-Aug-13 6:10am
   
You may rewrite like this
 
string datestring = Request.Form[registrationDateTextBox.UniqueID];
RashaSalim at 21-Jun-13 9:05am
   
Many thanks to you I have been searching for this :)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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 Smile | :)
  Permalink  
v2
Comments
MAC123456 at 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 at 4-Jun-12 7:50am
   
Local time or UTC?
Cheers
Andi
Linto Leo Tom at 4-Jun-12 9:57am
   
Due to Convert.ToDateTime
Meher Khan at 15-May-14 13:00pm
   
great bro.. this give me a great result as i want +1
Linto Leo Tom at 15-May-14 14:13pm
   
:)
Manoj B. Kalla at 29-Sep-14 6:10am
   
Thank you..
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Dates are the most locale-specific things of all. Smile | :)
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.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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.
  Permalink  
Comments
Shahin Khorshidnia at 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 ;) )
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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]);
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hello,
 
In you case try to avoid fill date from user instand of that use calendar control for date.
Note:
When ever date and time is concern you should always follow your database sever format.
  Permalink  
v2
Comments
MAC123456 at 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 at 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 at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

  Permalink  

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



Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 31 Mar 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100