C# - 如何验证日期时间(使“20120713”或“120713” TO“13.07.2012”)

2019-07-30 15:55发布

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.YYY" in C#.

I have no idea how many diferent date-formats are in the diferent EDI-Orders, so i'm searching for a solution i can apply to all of them.

thanks everybody.

Answer 1:

你应该有兴趣使用的此重载ParseExact ,您可以用多种格式传递作为数组,它会尝试它基于它们进行解析。(这将是很好,如果你可以控制的格式,并打算使用一个用于进程)

DateTime start = DateTime.ParseExact("20120713",
                    new[] { "yyyyMMdd", "yyMMdd" },
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None);
DateTime end = DateTime.ParseExact("120713",
                    new[] { "yyyyMMdd", "yyMMdd" },
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None);

为了您的输出,你可以做start.ToString("dd.MM.yyyy")



Answer 2:

这应该适用于多种格式

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 */ }


文章来源: C# - How To Validate DateTime ( make “20120713” OR “120713” TO “13.07.2012” )