String was not recognized as a valid DateTime " format dd/MM/yyyy"

C#.NetDatetimeTypesCasting

C# Problem Overview


I am trying to convert my string formatted value to date type with format dd/MM/yyyy.

this.Text="22/11/2009";

DateTime date = DateTime.Parse(this.Text);

What is the problem ? It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?

Edit

What are the differences between Parse and ParseExact?

Edit 2

Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.

Which answer is better considering all aspects like type saftey, performance or something you feel like

C# Solutions


Solution 1 - C#

Use DateTime.ParseExact.

this.Text="22/11/2009";

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

Solution 2 - C#

You need to call ParseExact, which parses a date that exactly matches a format that you supply.

For example:

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.

Solution 3 - C#

Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);

For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).

Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.

For example, this will parse your date correctly:

DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );

Of course, you shouldn't just randomly pick France, but something appropriate to your needs.

What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.

Solution 4 - C#

Although the above solutions are effective, you can also modify the webconfig file with the following...

<configuration>
   <system.web>
     <globalization culture="en-GB"/>
   </system.web>
</configuration>

Ref : https://stackoverflow.com/questions/3768061/datetime-format-different-on-local-machine-compared-to-production-machine

Solution 5 - C#

You might need to specify the culture for that specific date format as in:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy

    this.Text="22/11/2009";

    DateTime date = DateTime.Parse(this.Text);

For more details go here:

http://msdn.microsoft.com/en-us/library/5hh873ya.aspx

Solution 6 - C#

Based on this reference, the next approach worked for me:

// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017" 
var formatInfo = new DateTimeFormatInfo()
{
     ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);

Solution 7 - C#

After spending lot of time I have solved the problem

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

Solution 8 - C#

private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

Solution 9 - C#

use this to convert string to datetime:

Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)

Solution 10 - C#

Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:

date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"

to convert it to: '20130121' you use:

date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);

so that SQL can convert it and put it into your database.

Solution 11 - C#

Worked for me below code:

DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));

Namespace

using System.Globalization;

Solution 12 - C#

You can use also

this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
                                    Convert.ToInt32(this.Text.Substring(2,2)), // Month
                                    Convert.ToInt32(this.Text.Substring(0,2)));// Day

Solution 13 - C#

Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Solution 14 - C#

Change Manually :

string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);

From 11/22/2015 it will be converted in 22/11/2015

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShantanu GuptaView Question on Stackoverflow
Solution 1 - C#Samuel NeffView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#GregView Answer on Stackoverflow
Solution 4 - C#Amit PhilipsView Answer on Stackoverflow
Solution 5 - C#Ricardo SanchezView Answer on Stackoverflow
Solution 6 - C#Jesús CastroView Answer on Stackoverflow
Solution 7 - C#Mohammad Atiour IslamView Answer on Stackoverflow
Solution 8 - C#Bala KumarView Answer on Stackoverflow
Solution 9 - C#AshifJMView Answer on Stackoverflow
Solution 10 - C#j.rmz87View Answer on Stackoverflow
Solution 11 - C#Anjan KantView Answer on Stackoverflow
Solution 12 - C#Serkan HekimogluView Answer on Stackoverflow
Solution 13 - C#RJNView Answer on Stackoverflow
Solution 14 - C#sartaView Answer on Stackoverflow