简体   繁体   English

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

[英]DateTime.TryParseExact returns false for some string in c#

I am facing an issue in the parsing of the date. 我在解析日期时遇到问题。 I have made following common function. 我做了以下常用功能。

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;
            }
        }

But very strange thing happens some strings are successfully converted into DateTime but some return false. 但是非常奇怪的事情发生了,有些字符串已成功转换为DateTime,但有些返回false。

For example : 例如 :

"2017-05-11 12:00:24" this string parse successfully. “ 2017-05-11 12:00:24”此字符串成功解析。

"2015-03-06 20:18:42" this string can not. “ 2015-03-06 20:18:42”此字符串不能。

The format of the string is same. 字符串的格式相同。

I observed that when "hour(hh)" goes above 12 then it cannot be parsed. 我观察到,当“ hour(hh)”超过12时,就无法解析它。

You need to change yyyy-MM-dd hh:mm:ss to yyyy-MM-dd HH:mm:ss, which is hours in 24 hour time. 您需要将yyyy-MM-dd hh:mm:ss更改为yyyy-MM-dd HH:mm:ss,即24​​小时制的小时数。 Note the change from hh to HH. 注意从hh到HH的更改。

See here: C# DateTime to "YYYYMMDDHHMMSS" format 参见此处: C#DateTime为“ YYYYMMDDHHMMSS”格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM