Question of formatting a string to DateTime

  • Thread starter Thread starter Bill
  • Start date Start date
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?
 
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);
 
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,
 
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.
 
Hi

Sorry but I sent it without the code

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

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

Back
Top