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

Rut*_*hta 0 c# asp.net xamarin c#-6.0 xamarin.forms

我在解析日期时面临一个问题.我做了以下常用功能.

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是很奇怪的事情发生了一些字符串被成功转换为DateTime但有些字符串返回false.

例如 :

"2017-05-11 12:00:24"这个字符串解析成功.

"2015-03-06 20:18:42"这个字符串不行.

字符串的格式相同.

我观察到,当"小时(hh)"超过12时,则无法解析.

Gre*_*ous 7

您需要将yyyy-MM-dd hh:mm:ss更改为yyyy-MM-dd HH:mm:ss,这是24小时内的小时数.注意从hh到HH的变化.

请参见此处:C#DateTime为"YYYYMMDDHHMMSS"格式