By Shantanu Gupta


2010-02-03 15:24:29 8 Comments

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

14 comments

@David Castro 2018-04-24 22:19:38

An easy way without external references:

public string FormatDate(string date, string format)
{
   try {
      return DateTime.Parse(date).ToString(format);
   }
   catch (FormatException) 
   {
      return string.Empty;
   }
}

@Jesús Castro 2017-07-25 14:46:33

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);

@Anjan Kant 2016-09-19 10:49:39

Worked for me below code:

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

Namespace

using System.Globalization;

@sarta 2015-07-23 20:10:02

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

@fusion27 2018-06-15 11:27:38

I don't want to work that hard!

@atik sarker 2014-03-31 05:43:46

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]);

@Samuel Neff 2010-02-03 15:27:40

Use DateTime.ParseExact.

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

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

@Shantanu Gupta 2010-02-03 15:29:22

Why we have to pass null here ?

@Jon Skeet 2010-02-03 15:33:24

null means "the current culture"... as documented in MSDN. (If you don't know what's going on, consulting the documentation is a good first step.)

@Rahatur 2012-02-24 09:11:38

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?

@Samuel Neff 2012-02-27 02:22:31

@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.

@Alvin Wong 2013-03-25 16:51:19

@SamuelNeff Why don't you use CultureInfo.InvariantCulture instead of the current one if you are defining a format anyway?

@Samuel Neff 2013-03-25 21:02:22

@AlvinWong, either one works fine. Since we're defining a specific format, the culture doesn't matter in this case.

@Toolkit 2015-02-08 03:35:26

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);

@Jeppe Stig Nielsen 2015-07-27 08:51:30

@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).

@Jenish Zinzuvadiya 2016-04-08 11:07: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 and parse time ticks C#

@Ghanshyam Lakhani 2017-07-17 07:24:47

@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,,

@Samuel Neff 2017-07-17 22:44:55

@GhanshyamLakhani what format string are you using? it should be "dd/MM/yy".

@Mbithy Mbithy 2017-08-02 16:01:18

@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

@G Jeny Ramirez 2013-01-21 23:56:33

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.

@Bala Kumar 2013-02-15 06:40:40

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;
}

@Amit Philips 2012-11-17 13:39:37

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

@RNH 2013-07-26 06:20:53

Amit Philips, you saved my day.. I had tried all possible things. And this small change works. Thanks.

@Amit Philips 2013-07-26 10:00:43

thanks @RNH glad it helped :)

@The Furious Bear 2015-03-02 12:21:37

Amit, you are truly the son of God.

@Ghanshyam Lakhani 2017-07-17 07:44:38

@AmitPhilips your solution fantastic...this works for me.....

@ronydavid 2019-01-29 18:16:14

your are the best man.. this really works...

@AshifJM 2010-06-29 13:24:39

use this to convert string to datetime:

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

@Serkan Hekimoglu 2010-06-29 13:28:37

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

@Greg 2010-02-03 15:56:15

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.

@Ghanshyam Lakhani 2017-07-17 07:32:19

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.

@Greg 2017-07-17 15:05:57

Please share your code

@Ricardo Sanchez 2010-02-03 17:06:48

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

@Crismogram 2018-10-19 20:45:24

this works for me on working with old examples.

@SLaks 2010-02-03 15:28:20

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.

@Shantanu Gupta 2010-02-03 15:31:49

@Slaks: CultureInfo.InvariantCulture is not availabe in code. Do i need to use some namespace

@SLaks 2010-02-03 15:32:31

using System.Globalization;

@Inkey 2014-01-08 16:36:51

You can also right click on the error and click resolve this will put in the missing namespace for you.

@Usman Younas 2015-04-14 07:17:49

you can also double click the error and see an arrow down showing related namespaces you can use

@Chris Halcrow 2017-07-04 06:39:03

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

@Ghanshyam Lakhani 2017-07-17 07:25:53

@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.

Related Questions

Sponsored Content

41 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

59 Answered Questions

[SOLVED] What is the difference between String and string in C#?

15 Answered Questions

[SOLVED] C# DateTime to "YYYYMMDDHHMMSS" format

  • 2010-06-11 18:43:49
  • SARAVAN
  • 1215697 View
  • 543 Score
  • 15 Answer
  • Tags:   c# datetime

22 Answered Questions

[SOLVED] Converting string into datetime

  • 2009-01-21 18:00:29
  • Oli
  • 2352266 View
  • 1811 Score
  • 22 Answer
  • Tags:   python datetime

36 Answered Questions

[SOLVED] Should I use the datetime or timestamp data type in MySQL?

15 Answered Questions

24 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

32 Answered Questions

[SOLVED] How do I check if a string is a number (float)?

38 Answered Questions

4 Answered Questions

[SOLVED] Parsing datetime in textbox

Sponsored Content