我尝试过如下:
DateTime.ParseExact("Feb520161000PM", "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)但是它给了 FormatException 。
有趣的是
DateTime.ParseExact(DateTime.Now.ToString("MMMdyyyyhhmmtt"), "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)这也是给格式异常
推荐答案Alexei的回答是对的,如果你让我,我想解释一点点..
Alexei's answer is quite right, I wanna explain little bit deep if you let me..
你在想 5 应该符合 d 说明符,对吧?但这不是如何 DateTime.ParseExact 工作在引擎盖下。
You are thinking 5 should match with d specifier, right? But this is not how DateTime.ParseExact works under the hood.
由于 d自定义格式说明符代表 1 code> 31 ,此说明符将在您的字符串中映射 52 ,不只需 5 。这就是为什么你的代码抛出 FormatException 。
Since The "d" custom format specifier represents number from 1 through 31, this specifier will map 52 in your string, not just 5. That's why your code throws FormatException.
正如你所看到的,你的字符串格式不能解析除非使用它进行一些字符串操作。
As you can see, your string format can't parsed unless you do it some string manipulations with it.
在这种情况下,.NET Team 建议使用两个数字格式,例如 05 ,或插入分隔符以用于日期和时间值。
In such a case, .NET Team suggests either using two digit forms like 05 or insert separators for your date and time values.
您可以创建一个自定义方法,解析仅限 的 MMMdyyyhhmmtt 格式解析此类格式的字符串, p>
You can create a custom method that parse this MMMdyyyyhhmmtt format for only parse this kind of formatted strings like;
public static DateTime? ParseDate_MMMdyyyyhhmmtt(string date) { if (date == null) return null; if (date.Length < 14) return null; if (date.Length == 14) date = date.Insert(3, "0"); DateTime dt; if (DateTime.TryParseExact(date, "MMMdyyyyhhmmtt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) return dt; return null; }更多推荐
如何将格式为MMMdyyyyhhmmtt的datetime字符串转换为datetime对象?
发布评论