views:

137

answers:

4
+1  Q: 

String to datetime

I have a string 12012009 input by the user in ASP.NET MVC application. I wanted to convert this to a DateTime.

But if I do DateTime.TryParse("12012009", out outDateTime); it returns a false.

So I tried to convert 12012009 to 12/01/2009 and then do DateTime.TryParse("12/01/2009", out outDateTime); which will work

But I don't find any straight forward method to convert string 12012009 to string "12/01/2009". Any ideas?

+2  A: 

You can use the DateTime.TryParseExact and pass in the exact format string:

DateTime dateValue = DateTime.Now;
if (DateTime.TryParseExact("12012009", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)))
{
   // Date now in dateValue
}
Oded
`mm` is the format specifier for *minute*. http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
dtb
@dtb - Thanks for the catch!
Oded
+8  A: 

First, you need to decide if your input is in day-month-year or month-day-year format.

Then you can use DateTime.TryParseExact and explicitly specify the format of the input string:

DateTime.TryParseExact("12012009",
                       "ddMMyyyy",
                       CultureInfo.InvariantCulture,
                       DateTimeStyles.None,
                       out convertedDate)

See also: Custom Date and Time Format Strings

dtb
+1 beat me to it.... :-)
marc_s
This is the answer, but it depends on single digit months/days being prefixed with a 0. If 1212009 is a possible input, you are hosed.
Serapth
Thanks. The input will definitely be in mmddyyyy format. So I think I am safe.
SARAVAN
@Serapth: you can actually provide **multiple format strings** to TryParseExact - one for the case with ddMMyyyy, another for dMMyyyy etc.
marc_s
@marc_s True, but tell me, what do you do with 1112009? :-)
Serapth
@Serapth: sure - you can't have all possible combinations - but something like "dMMyyyy" and "ddMMyyyy" could be a plausible case
marc_s
A: 

If you want to use that format you will most likely need to specify the format to the parser. Check the System.IFormatProvider documentation as well as the System.DateTime documentation for methods that take an IFormatProvider.

confusedGeek
A: 
DateTime yourDate = 
    DateTime.ParseExact(yourString, "ddMMyyyy", Culture.InvariantCulture);
Taylor Leese