C# 对于c中的某些字符串,DateTime.TryParseExact返回false#

C# 对于c中的某些字符串,DateTime.TryParseExact返回false#,c#,asp.net,xamarin,xamarin.forms,c#-6.0,C#,Asp.net,Xamarin,Xamarin.forms,C# 6.0,我在解析日期时遇到了一个问题。我做了如下的共同功能 public static string ConvertedDate(string date) { if(!string.IsNullOrEmpty(date)) { DateTime returnValue; bool flag = DateTime.TryParseExact(date, "yyyy-MM-dd h

我在解析日期时遇到了一个问题。我做了如下的共同功能

public static string ConvertedDate(string date)
        {
            if(!string.IsNullOrEmpty(date))
            {
                DateTime returnValue;
                bool flag = DateTime.TryParseExact(date, "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out returnValue);
                return flag ? returnValue.ToString("MM.dd.yyyy") : null;
            }
            else
            {
                return null;
            }
        }
但发生了一件非常奇怪的事情,有些字符串成功地转换为DateTime,但有些字符串返回false。

例如:

“2017-05-11 12:00:24”此字符串解析成功

“2015-03-06 20:18:42”此字符串不能使用

字符串的格式相同


我观察到,当“小时(hh)”超过12时,它就无法被解析。

您需要将yyyy-MM-dd hh:MM:ss更改为yyy-MM-dd hh:MM:ss,即24小时时间中的小时。注意从hh到hh的变化


请参见此处:

您的观察结果应该会告诉您一些事情……也许这不是正确的格式?请参见格式。