217

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

Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286
  • 7
    @Edit: That's what the documentation is for. http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx – SLaks Feb 03 '10 at 15:32
  • 2
    ParseExact is for when you know the exact format of the date string, Parse is when you want something which can handle something a bit more dynamic. – gingerbreadboy Feb 03 '10 at 16:05

13 Answers13

313

Use DateTime.ParseExact.

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

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • 19
    Why we have to pass null here ? – Shantanu Gupta Feb 03 '10 at 15:29
  • 3
    Input can be "22/11/2009 12:00:00 AM" or "22/11/2009". Also the culture of the development machine can be different from the culture of the production. So will the above code work seamlessly? – Rahatur Feb 24 '12 at 09:11
  • 10
    @Rahat, parse exact will not work if the format doesn't match. The format pattern above is `dd/MM/yyyy` so a text string with a time in it will not be parsed properly. You'll need to either strip off the time or include it in the format pattern. There's an overload of `ParseExact` that accepts an array of format patterns and will parse the text if it matches any of them. – Samuel Neff Feb 27 '12 at 02:22
  • 8
    @SamuelNeff Why don't you use `CultureInfo.InvariantCulture` instead of the current one if you are defining a format anyway? – Alvin Wong Mar 25 '13 at 16:51
  • @AlvinWong, either one works fine. Since we're defining a specific format, the culture doesn't matter in this case. – Samuel Neff Mar 25 '13 at 21:02
  • 2
    I am not sure what the heck but this var text = "22/11/2009"; DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy", null); throws String was not recognized as a valid DateTime. exception. You must use DateTime.ParseExact(Text, "dd/MM/yyyy", CultureInfo.InvariantCulture); – Toolkit Feb 08 '15 at 03:35
  • 3
    @Toolkit The reason is that the slashes in the format string are not literal slashes. They are substituted by the date separator string in the current culture. So it does depend on the culture in the way it is written above. Samuel Neff, try `Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");`, it will break your solution. To fix that, use `"dd'/'MM'/'yyyy"` (protecting the slashes with single quotes), or `@"dd\/MM\/yyyy"` ("escaping" the slashed with backslashes). – Jeppe Stig Nielsen Jul 27 '15 at 08:51
  • If you use time ticks to get and set the date you may get benefit to not set the culture and time ticks are generally language independent. You can follow this link for [ticks](https://msdn.microsoft.com/en-us/library/system.datetime.ticks(v=vs.110).aspx) and [parse time ticks C#](http://stackoverflow.com/questions/18964370/converting-ticks-to-datetime) – Jenish Zinzuvadiya Apr 08 '16 at 11:07
  • @SamuelNeff your solution not work for me it gives error like " String was not recognized as a valid DateTime." and i'm passing following input date : "13/06/17" to your solution but it gives error.plz help me,, – Ghanshyam Lakhani Jul 17 '17 at 07:24
  • @GhanshyamLakhani what format string are you using? it should be `"dd/MM/yy"`. – Samuel Neff Jul 17 '17 at 22:44
  • @JonSkeet person wanted a copy paste and go solution. This is why the correct answer gave them an error. They pasted dd/MM/yyyy while their exact string was dd/MM/yy, they then begun fixing issues with slashes :-D – Mbithy Mbithy Aug 02 '17 at 16:01
  • @SamuelNeff can you share code snippets for parseExact overload passing format pattern. Little late to the discussion – Amit Jan 21 '20 at 12:05
  • 1
    @Amit I'm not sure what you're asking. The example above includes the format pattern. – Samuel Neff Jan 28 '20 at 02:21
56

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.

Greg
  • 16,540
  • 9
  • 51
  • 97
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    @Slaks: CultureInfo.InvariantCulture is not availabe in code. Do i need to use some namespace – Shantanu Gupta Feb 03 '10 at 15:31
  • 3
    `using System.Globalization;` – SLaks Feb 03 '10 at 15:32
  • 2
    You can also right click on the error and click resolve this will put in the missing namespace for you. – Inkey Jan 08 '14 at 16:36
  • you can also double click the error and see an arrow down showing related namespaces you can use – Usman Younas Apr 14 '15 at 07:17
  • Spaces count too, so for example if your string format is "MM/dd/yyyy HH:mm:ss" (note - *2* spaces) - then your format for ParseExact must also include the spaces – Chris Halcrow Jul 04 '17 at 06:39
  • @SLaks your solution not work for me it gives error like " String was not recognized as a valid DateTime." and i'm passing following input date : "13/06/17" to your solution but it gives error.Plz help me. – Ghanshyam Lakhani Jul 17 '17 at 07:25
  • This worked for me. I am testing locales and my string date "MM/dd/yyyy" was throwing on ES locale. Thank you – Jeff Blumenthal Jul 14 '21 at 17:24
23

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.

Greg
  • 16,540
  • 9
  • 51
  • 97
  • your solution not work for me it gives error like " String was not recognized as a valid DateTime." and i'm passing following input date : "13/06/17" to your solution but it gives error.Plz help me. – Ghanshyam Lakhani Jul 17 '17 at 07:32
18

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 : Datetime format different on local machine compared to production machine

Community
  • 1
  • 1
Amit Philips
  • 387
  • 6
  • 17
13

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

Ricardo Sanchez
  • 6,079
  • 3
  • 24
  • 31
8

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);
Jesús Castro
  • 2,061
  • 1
  • 22
  • 26
6
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;
}
Bala Kumar
  • 637
  • 3
  • 11
  • 18
6

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]);
Undo
  • 25,519
  • 37
  • 106
  • 129
Mohammad Atiour Islam
  • 5,380
  • 3
  • 43
  • 48
4

use this to convert string to datetime:

Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
stema
  • 90,351
  • 20
  • 107
  • 135
AshifJM
  • 41
  • 1
1

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.

bluish
  • 26,356
  • 27
  • 122
  • 180
j.rmz87
  • 786
  • 1
  • 7
  • 18
1

Worked for me below code:

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

Namespace

using System.Globalization;
Anjan Kant
  • 4,090
  • 41
  • 39
0

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
Serkan Hekimoglu
  • 4,234
  • 5
  • 40
  • 64
0

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

RJN
  • 696
  • 8
  • 17