如何将格式为MMMdyyyyhhmmtt的datetime字符串转换为datetime对象? [英] How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?
问题描述
我尝试过如下:
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对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!