I\'m trying to parse a DateTime from EDI-Order ( \"20120713\" / YYYYMMDD or \"120713\" / YYMMDD or even other dates WITHOUT dots, so just numbers ) to a valied Date like \"DD.MM
You should be interested in using this overload of ParseExact
, you can pass in multiple formats as an array and it will attempt to parse it based on them.(it would be good if you can control the formats and intend on using one for the process)
DateTime start = DateTime.ParseExact("20120713",
new[] { "yyyyMMdd", "yyMMdd" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
DateTime end = DateTime.ParseExact("120713",
new[] { "yyyyMMdd", "yyMMdd" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
For your output you can do start.ToString("dd.MM.yyyy")
This should work for multiple formats
DateTime Result = new DateTime();
string[] dateFormats = new string[]{ "YYYYMMDD", "YYMMDD", /*other formats you might need*/ };
if (dateFormats.Any(format => DateTime.TryParseExact("yourDate", format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out Result)))
{ /* Result contains the parsed DateTime and you can use it*/ }
else
{ /* DateTime couldn't be parsed for any format you specified */ }