Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing any date format string to datetime [closed]

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.

like image 237
Andris Mudiayi Avatar asked Jul 23 '13 14:07

Andris Mudiayi


2 Answers

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
like image 50
phillip Avatar answered Oct 26 '22 23:10

phillip


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

like image 20
Tim Schmelter Avatar answered Oct 26 '22 23:10

Tim Schmelter