5

I am trying to parse the date by using below code

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 

but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017

looking forward for your valuable answers...

Isham Khan
  • 105
  • 7
  • Possible duplicate of [Parse string to DateTime in C#](http://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – J. Tuc Mar 30 '17 at 08:16

3 Answers3

13

Lowercase mm means minute, use MM

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 

If you want to output it as 30/Mar/2017(different topic):

string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);

But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
7

replace

"dd/mm/yyyy" 

with

"dd/MMM/yyyy" 

because "Jan" is matched by MMM instead of mm (for minutes)

Reference

"MMM" The abbreviated name of the month.

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

fubo
  • 44,811
  • 17
  • 103
  • 137
1

The date format is wrong. try "dd/MM/yyyy" instead of "dd/mm/yyyy"

If you need abbrivated month name, use "dd/MMM/yyyy"

Santhosh
  • 729
  • 7
  • 19