将包含多种格式日期的字符串转换为包含 "CCYYMMDD" 格式日期的字符串

Convert string containing a date in multiple formats to a string containing a date in the "CCYYMMDD" format

我有一个包含日期和时间的字符串。日期采用以下任一格式:
M/D/YYYY”或“MM/D/YYYY”或“M/DD/YYYY”或“MM/DD/YYYY”。
时间在:
hh:mm:ss”或“h:mm:ss”。
使用 C# 代码从 SQL 服务器检索字符串。

如何将其转换为格式为“CCYYMMDD”的包含日期的字符串?

        var inputDate = "4/28/2006 12:39:32:429AM";

        //1 - parse into date parts
        char[] delimiterChars = { '/' };

        string[] dateParts = inputDate.Split(delimiterChars);
        var month = int.Parse(dateParts[0].ToString());
        var day = int.Parse(dateParts[1].ToString()); 
        var year = 0;

        string yearString = dateParts[2].ToString();

        //strip of the time for the year part
        if (yearString.Length > 5)
            year = int.Parse(yearString.Substring(0, 4));

        //2 - Create date object
        DateTime testDate = new DateTime(year, month, day);

        //3 - format date
        var outputDate = testDate.ToString("yyyyMMdd");

        Console.WriteLine("Input date: " + inputDate);
        Console.WriteLine("Output date: " + outputDate);

        Console.ReadLine();

你可以参考MSDN格式化日期here。您可能还想做一些验证以确保您从 SQL 服务器获得有效日期。

其实这样更好。我不知道我之前在想什么.. 使用 DateTime.TryParse 方法验证字符串是否为日期。如果 TryParse 返回为 false,则字符串不是有效的日期格式。您在要求中期望的格式是有效的日期格式。

        DateTime date;

        var inputDate = "4/28/2006 12:39:32";
        var outputDate = "Could not format the date.  The input date is not in a correct date format!";

        if (DateTime.TryParse(inputDate,out date))
        {
            outputDate = date.ToString("yyyyMMdd");
        }

        Console.WriteLine("Input date: " + inputDate);
        Console.WriteLine("Output date: " + outputDate);

        Console.ReadLine();