Question of formatting a string to DateTime

B

Bill

I am being passed a string value in the form of MMddyyyy that needs to be
converted to DateTime. Do I need to first convert the string to MM/dd/yyyy
before calling the DateTime.Parse(string) method?
 
K

Kyril Magnos

Nope, just use DateTime.Parse(). It should parse it without problems.

HTH,

Kyril
 
S

Shakir Hussain

You can have space characters though to parse using
DateTimeStyles.AllowWhiteSpaces.

In your case, you may have to insert "/". If month and day are switched, you
have to specify FormatProvider in the argument.

IFormatProvider culture = new CultureInfo("en-US", true);

Try this

string myDate= "02 22 2004";
IFormatProvider culture = new System.Globalization.CultureInfo("en-US",
true);
DateTime a =
DateTime.Parse(myDate,culture,System.Globalization.DateTimeStyles.AllowWhite
Spaces);
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Bill,


The best way of do it is using DateTime.ParseExact() this method let you
especify the format of the string being converted, in your case you can try

DateTime.ParseExact( stringToConvert,


Cheers,
 
B

Bill

Sounds like I will have to insert / or space. For example, if I'm passed
12102001 I will need to convert it to either 12/10/2001 or 12 10 2001.

Not difficult, but I was thinking there might be something more natural,
such as a format string.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi

Sorry but I sent it without the code

The code looks like:
DateTime.ParseExact( stringToConvert, , "MMddyyyy", null );

Cheers,
 
B

Bill

Ah, perfect. That's exactly what I was hoping for... although a little
surprised they didn't overload this option for DateTime.Parse().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top