在.NET自定义日期格式的日期时间解析 [英] DateTime parsing of custom date format in .NET
问题描述
我有形式ORDER20100322194007
,它20100322194007
日期和时间<$ C的字符串$ C> 2010-03-22 19:40:07.000 。如何解析字符串并获得所包含的对象的DateTime
?
I have a string of the form "ORDER20100322194007"
, it "20100322194007"
Date and time 2010-03-22 19:40:07.000
. How to parse a string and get the contained object DateTime
?
推荐答案
将它总是与订单
?
string pattern = "'ORDER'yyyyMMddHHmmss";
DateTime dt;
if (DateTime.TryParseExact(text, pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
// dt is the parsed value
}
else
{
// Invalid string
}
如果字符串是无效的应该抛出一个异常,然后使用 DateTime.ParseExact
,而不是 DateTime.TryParseExact
If the string being invalid should throw an exception, then use DateTime.ParseExact
instead of DateTime.TryParseExact
如果它并不总是以订单,然后做任何你需要在开始为了得到公正的日期和时间部分,并从上面的格式模式'订单'。
If it doesn't always begin with "ORDER" then do whatever you need to in order to get just the date and time part, and remove "'ORDER'" from the format pattern above.
这篇关于在.NET自定义日期格式的日期时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!