Parse a string containing date and time in a custom format

C#ParsingDatetimeTime

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You can use DateTime.ParseExact method to specify the format that should be used while parsing.

Solution 3 - C#

If you don't have a fixed structure of your string say order will not always be there then you can use regex to separate the numbers and characters and then use convert to datetime function for the numbers separated.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionakrisanovView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#GiorgiView Answer on Stackoverflow
Solution 3 - C#SamikshaView Answer on Stackoverflow