礼貌有其需要的格式,试图数组,并允许您指定空格是允许的DateTime.ParseExact过载:
string[] ss = new string[] { "Jun 29 2016 6:59PM", "Jan 1 1900 12:00AM " };
string[] formats = new string[] { "MMM dd yyyy h:mmtt", "MMM d yyyy hh:mmtt", "MMM dd yyyy hh:mmtt", "MMM d yyyy h:mmtt" };
foreach (string s in ss)
{
Console.WriteLine(DateTime.ParseExact(s, formats, null, DateTimeStyles.AllowWhiteSpaces).ToString("yyyy-MM-dd HH:mm:ss"));
}
但是如果您的日期字符串有点疏忽,您可以使用TryParse
代替:
DateTime d;
foreach (string s in ss)
{
if (DateTime.TryParse(s, out d))
{
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
您应该指定一个System.IFormatProvider。
您能澄清[自定义日期和时间格式字符串]的哪一部分(https://msdn.microsoft.com/en-us/library/8kb3ddd4(v = vs.110))。aspx)对日期格式不清楚(比如''d“'与''dd”'区别)? –
请注意,帖子的标题与您遇到的问题完全无关 - 您可能需要重新阅读[MCVE]关于为帖子创建示例代码的指导。 –
检查日期字符串中的尾部空格 – Fabio