DateTime.PraseExact无法将字符串识别为有效的datetime异常

Hen*_*ues 1 c# datetime

我想将日期时间转换为特定格式,然后将其保存到Object类型的变量中,但由于无法将String识别为有效的DateTime,因此我遇到了错误

在我尝试过的代码下面

string regDate = DateTime.ParseExact("05/07/2015 19:41:06 PM", "MM-dd-yyyy HH:mm tt", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

输入将采用“ 05/07/2015 19:41:06 PM”的格式,我也希望以mm / dd / yyyy格式输出带有小时-分钟-秒的格式。

Chr*_*tos 5

您得到的错误是合理的,因为您传递的字符串的格式不正确,因此您传递给ParseExact

请尝试以下操作:

var regDate = DateTime.ParseExact("05/07/2015 19:41:06 PM", "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

此外,不需要像在此那样将字符串转换为字符串Convert.ToString("05/07/2015 19:41:06 PM")

检查此.NET Fiddle