如何在 C# 中将 Feb 19, 2015,22:19:50 转换为 2/19/2015 22:19:50?

How to convert Feb 19, 2015,22:19:50 to 2/19/2015 22:19:50 in C#?

如何在 C# 中将 Feb 19, 2015,22:19:50 转换为 2/19/2015 22:19:50

我试过类似下面的方法

DateTime dateTime = DateTime.ParseExact("Feb 19, 2015,22:19:50",
                                        "MMM dd, yyyy;HH:mm:ss",
                                        CultureInfo.InvariantCulture);

但是我得到了以下错误

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: String was not recognized as a valid DateTime."

首先,您的字符串和格式不完全匹配。在您的字符串中,年份和小时之间有一个逗号,但在您的格式中有一个分号。当您使用 DateTime.ParseExactDateTime.TryParseExact 方法进行自定义解析时,您的字符串和格式必须根据您使用的 IFormatProvider 完全匹配。

正确解析字符串后,您可以使用 .ToString() 方法将其格式化为 M/dd/yyyy HH:mm:ss 格式和具有 / 作为 DateSeparator: 作为 TimeSeparator 就像 InvariantCulture.

string s = "Feb 19, 2015,22:19:50";
DateTime dt;
if(DateTime.TryParseExact(s, "MMM dd, yyyy,HH:mm:ss", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
   Console.WriteLine(dt.ToString("M/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
   // 2/19/2015 22:19:50
}

这里是demonstration.