以自定义格式解析包含日期和时间的字符串 [英] Parse a string containing date and time in a custom format
本文介绍了以自定义格式解析包含日期和时间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个下一个格式为"ORDER20100322194007"
的字符串,其中20100322
是日期,而194007
是时间.如何解析字符串并获取包含的DateTime
对象?
I have a string of the next format "ORDER20100322194007"
, where 20100322
is a date and 194007
is a time. How to parse a string and get the contained DateTime
object?
推荐答案
是否总是以ORDER
开头?
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
如果它并不总是以"ORDER"开头,则需要做任何事情以获取日期和时间部分,并从上面的格式模式中删除'ORDER'".
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.
这篇关于以自定义格式解析包含日期和时间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文