Reputation: 26498
I have a problem while converting a string whose value is dd.mm.yyyy
to DateTime
in c#
string OriginalDateFormat = "28.06.2009";
DateTime dt= Convert.ToDateTime(OriginalDateFormat);
Throwing an exception "String was not recognized as a valid DateTime."
But if it is in mm.dd.yyyy
then it is running fine.
I googled and got lots of sites but all in vain
Any idea?
Thanks in advance.
Upvotes: 1
Views: 1268
Reputation: 1500145
Use DateTime.ParseExact
and specify the exact format string:
DateTime dt = DateTime.ParseExact("28.06.2009", "dd'.'MM'.'yyyy",
CultureInfo.InvariantCulture);
If this is the value is from user input, you probably want to use DateTime.TryParseExact so you can handle failure gracefully:
DateTime dt;
if (DateTime.TryParseExact("28.06.2009", "dd'.'MM'.'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, // Default formatting options
out dt))
{
Console.WriteLine("Successfully parsed {0}", dt);
}
else
{
Console.WriteLine("Did not recognise date");
}
Upvotes: 9
Reputation: 4385
I think its an issue with culture...The format you specified is (I think) GB and the default culture is US. You will need to specify the culture also.
Instead try this:
IFormatProvider culture = new CultureInfo("en-US", true);//en-Us or en-GB not sure
DateTime dt = DateTime.Parse(p, culture, DateTimeStyles.AssumeLocal);
Upvotes: 3