Reputation: 15031
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?
Upvotes: 1
Views: 2180
Reputation: 498904
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
}
Upvotes: 4
Reputation: 217233
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
Upvotes: 9
Reputation: 52292
DateTime yourDate =
DateTime.ParseExact(yourString, "ddMMyyyy", Culture.InvariantCulture);
Upvotes: 0
Reputation: 2828
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.
Upvotes: 0