C# - How To Validate DateTime ( make “20120713” OR “120713” TO “13.07.2012” )

前端 未结 2 1184
温柔的废话
温柔的废话 2021-01-28 19:12

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

相关标签:
2条回答
  • 2021-01-28 19:44

    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")

    0 讨论(0)
  • 2021-01-28 19:51

    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 */ }
    
    0 讨论(0)
提交回复
热议问题