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?
-
1Thats a good question. Maybe you should change the title to something like "DateTime parsing of custom date format in .NET"Christian Klauser– Christian Klauser2010-04-01 13:32:25 +00:00Commented Apr 1, 2010 at 13:32
Add a comment
|
3 Answers
Will it always start with 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
}
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.
Comments
You can use DateTime.ParseExact method to specify the format that should be used while parsing.