In C#, how do I parse a string of format "dd/mm/yyyy"
or format "dd-mm-yyyy"
to datetime?
I get an error that says my string is not in the correct format. I need to be able to parse all the formats not just one of them.
You can define any format you like - plus you can get a list of defaults for a given culture.
var ci = new CultureInfo("en-US");
var formats = new[] { "M-d-yyyy", "dd-MM-yyyy", "MM-dd-yyyy", "M.d.yyyy", "dd.MM.yyyy", "MM.dd.yyyy" }
.Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray();
DateTime.ParseExact("07/23/2013", formats, ci, DateTimeStyles.AssumeLocal).Dump();
DateTime.ParseExact("07-23-2013", formats, ci, DateTimeStyles.AssumeLocal).Dump();
DateTime.ParseExact("23-07-2013", formats, ci, DateTimeStyles.AssumeLocal).Dump();
DateTime.ParseExact("23.07.2013", formats, ci, DateTimeStyles.AssumeLocal).Dump();
Output:
7/23/2013 12:00:00 AM
7/23/2013 12:00:00 AM
7/23/2013 12:00:00 AM
7/23/2013 12:00:00 AM
mm
means minute, uppercase MM
means month.
Apart from that, you have to use CultureInfo.InvariantCulture
if you want to parse strings with /
as date separator since this is the replacement char for your current culture's date separator:
So this works:
DateTime.ParseExact("23/07/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With