7

I am trying to convert a string into datetime with the following C# code,

DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);

eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.

What string format should I use to support both 01/01/2010 and 1/1/2010?

mamoo
  • 8,156
  • 2
  • 28
  • 38
Nevin Mathai
  • 2,316
  • 13
  • 39
  • 54
  • Not an exact dup, but this covers much the same territory: http://stackoverflow.com/questions/1368636/why-cant-datetime-parseexact-parse-9-1-2009-using-m-d-yyyy – DOK Jan 04 '10 at 17:09

3 Answers3

16

Using the following date format expression will allow you to use either single or double digit day and month elements.

"M/d/yyyy"

Note that the capital M is significant - a lower case m is the placeholder for minutes.

You will find more information related to date format strings here.

You can use the following Powershell command to test them.

[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
Scott Munro
  • 13,369
  • 3
  • 74
  • 80
3

Capital M is month, little m is mins i think.

But to the point of the question, use Parse. ParseExact implies you know the exact format of the input.

gingerbreadboy
  • 7,386
  • 5
  • 36
  • 62
1

You could try this format: MM/dd/yyyy, but I think there's no single format string that could support both inputs. You could test if the length of your dateTo string is less than 10 characters use M/d/yyyy, otherwise MM/dd/yyyy.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928