DateTime在.NET中解析自定义日期格式 [英] DateTime parsing of custom date format in .NET

查看:168
本文介绍了DateTime在.NET中解析自定义日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下一个格式的字符串ORDER20100322194007,其中20100322194007是一个日期和时间: 2010-03-22 19:40:07.000 如何解析字符串并获取包含的对象 DateTime

I have a string of the next format "ORDER20100322194007", where "20100322194007" is a date and time: 2010-03-22 19:40:07.000. How to parse a string and get the contained object DateTime?

推荐答案

是否始终以 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.

这篇关于DateTime在.NET中解析自定义日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆