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

前端 未结 2 1183
温柔的废话
温柔的废话 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")

提交回复
热议问题